【发布时间】:2018-08-04 03:00:46
【问题描述】:
我知道以下问题:
1.) How to split a column based on several string indices using pandas? 2.) How do I split text in a column into multiple rows?
不过,我想将它们分成几个新列。假设我有一个如下所示的数据框:
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
但是如何才能更优雅地实现相同的结果呢?a
【问题讨论】: