如何使用pandas Python将字符串拆分为多个列?

15

我知道以下问题:

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

但如何更优雅地实现相同的结果呢?

2个回答

20

str.split 方法有一个 expand 参数:

>>> df['string'].str.split(',', expand=True)
         0        1         2
0  astring      isa    string
1  another   string        la
2      123      232   another
>>>

列名为:

>>> df['string'].str.split(',', expand=True).rename(columns = lambda x: "string"+str(x+1))
   string1  string2   string3
0  astring      isa    string
1  another   string        la
2      123      232   another

使用Python >= 3.6的f-strings可以使代码更加简洁:

>>> (df['string'].str.split(',', expand=True)
...              .rename(columns=lambda x: f"string_{x+1}"))
  string_1 string_2  string_3
0  astring      isa    string
1  another   string        la
2      123      232   another

1
我如何将这些"string_x"列添加到原始数据框中? - ManojK
df[['new_column_1', 'new_column_2', 'new_column_3']] = above answer - Brian Yang

1

这种方法比expand选项稍微不太简洁,但是这是一种替代方案:

In [29]: cols = ['string_1', 'string_2', 'string_3']   

In [30]: pandas.DataFrame(df.string.str.split(', ').tolist(), columns=cols)
Out[30]: 
  string_1 string_2 string_3
0  astring      isa   string
1  another   string       la
2      123      232  another

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接