Pandas将列表列转换为文本列数据预处理



我有一个看起来像这样的数据集:

tbody> <<tr>
text
积极[耐嚼,‘什么’,‘dhepburn’,'说']
中性[耐嚼,‘+’,‘你’,‘我’,‘添加’]

我想你的问题是轴= 1你不需要这个

data = {
'sentiment' : ['positive', 'neutral'],
'text' : ["['chewy', 'what', 'dhepburn', 'said']", "['chewy', 'plus', 'you', 've', 'added']"]
}
df = pd.DataFrame(data)
df['text'] = df['text'].apply(lambda x : x.replace('[', '')).apply(lambda x : x.replace(']', '')).apply(lambda x : x.replace("'", ''))
df['text'] = df['text'].apply(lambda x : x.split(','))
df['text'] = df['text'].agg(' '.join)
df

使用join:

df['test'].str.join(' ')

示范:

df = pd.DataFrame({'test': [['chewy', 'what', 'dhepburn', 'said']]})
df['test'].str.join(' ')
输出:

0    chewy what dhepburn said
Name: test, dtype: object

基于注释:

#Preparing data
string = """sentiment   text
positive    ['chewy', 'what', 'dhepburn', 'said']
neutral ['chewy', 'plus', 'you', 've', 'added']"""
data = [x.split('t') for x in string.split('n')]
df = pd.DataFrame(data[1:], columns = data[0])
#Solution
df['text'].apply(lambda x: eval(x)).str.join(' ')

也可以更简单地使用:

df['text'].str.replace("[|]|'|,",'')

输出:

0    chewy what dhepburn said
1     chewy plus you ve added
Name: text, dtype: object

如果你有一个字符串表示的列表,你可以使用:

from ast import literal_eval
df['text'] = df['text'].apply(lambda x: ' '.join(literal_eval(x)))

如果你真的想去掉括号和逗号,使用regex:

df['text'] = df['text'].str.replace('[[',]]', '', regex=True)

输出:

sentiment                      text
0  positive  chewy what dhepburn said
1   neutral   chewy plus you ve added

最新更新