我知道以下问题:
1.) 如何使用 Pandas 根据多个字符串索引拆分列? 2.) 如何将列中的文本拆分成多个行?
但我希望将它们拆分成几个新列。假设我的数据框长这样:
id | string
-----------------------------
1 | astring, isa, string
2 | another, string, la
3 | 123, 232, another
我知道使用:
df['string'].str.split(',')
我可以将字符串进行分割。但是作为下一步,我希望能够高效地将分割后的字符串放入新的列中,就像这样:
id | string_1 | string_2 | string_3
-----------------|---------------------
1 | astring | isa | string
2 | another | string | la
3 | 123 | 232 | another
---------------------------------------
例如,我可以这样做:
for index, row in df.iterrows():
i = 0
for item in row['string'].split():
df.set_values(index, 'string_{0}'.format(i), item)
i = i + 1
但如何更优雅地实现相同的结果呢?
df[['new_column_1', 'new_column_2', 'new_column_3']] = above answer
- Brian Yang