【问题标题】:How do I split a string into several columns in a dataframe with pandas Python?如何使用 pandas Python 将字符串拆分为数据框中的几列?
【发布时间】: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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    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
    

    【讨论】:

    • 如何将这些 'string_x' 列添加到原始数据框>
    • df[['new_column_1', 'new_column_2', 'new_column_3']] = above answer
    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多