如何使用Pandas Python将字符串拆分为数据帧中的几列?

Tho*_*ale 5 python pandas

我知道以下问题:

1.)如何使用熊猫基于多个字符串索引拆分列? 2)如何将一列中的文本分成多行?

我想将它们分成几个新列。假设我有一个看起来像这样的数据框:

id    | string
-----------------------------
1     | astring, isa, string
2     | another, string, la
3     | 123, 232, another
Run Code Online (Sandbox Code Playgroud)

我知道使用:

df['string'].str.split(',')
Run Code Online (Sandbox Code Playgroud)

我可以分割一个字符串。但是,下一步,我想像这样有效地将拆分后的字符串放入新列中:

id    | string_1 | string_2 | string_3
-----------------|---------------------
1     | astring  | isa      | string
2     | another  | string   | la
3     | 123      | 232      | another
---------------------------------------
Run Code Online (Sandbox Code Playgroud)

我可以例如这样做:

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
Run Code Online (Sandbox Code Playgroud)

但是,如何才能更优雅地达到相同的结果呢?

jua*_*aga 14

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

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

使用列名:

>>> 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
Run Code Online (Sandbox Code Playgroud)

使用 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
Run Code Online (Sandbox Code Playgroud)