【发布时间】:2018-01-28 03:57:24
【问题描述】:
我正在尝试根据另一列字段中的某些标签和值解析 Pandas DataFrame 中的文本数据,并将它们存储在自己的列中。例如,如果我创建了这个数据框,df:
df = pd.DataFrame([[1,2],['A: this is a value B: this is the b val C: and here is c.','A: and heres another a. C: and another c']])
df = df.T
df.columns = ['col1','col2']
df['tags'] = df['col2'].apply(lambda x: re.findall('(?:\s|)(\w*)(?::)',x))
all_tags = []
for val in df['tags']:
all_tags = all_tags + val
all_tags = list(set(all_tags))
for val in all_tags:
df[val] = ''
df:
col1 col2 tags A C B
0 1 A: this is a value B: this is the b val C: and... [A, B, C]
1 2 A: and heres another a. C: and another c [A, C]
如何使用 col2 中的值填充每个新的“标签”列,以便得到这个 df:
col1 col2 tags \
0 1 A: this is a value B: this is the b val C: and... [A, B, C]
1 2 A: and heres another a. C: and another c [A, C]
A C B
0 this is a value and here is c. this is the b val
1 and heres another a. and another c
【问题讨论】:
标签: python regex pandas parsing dataframe