【问题标题】:How to split one column in a list into new columns when each list may have different number of members?当每个列表可能有不同数量的成员时,如何将列表中的一列拆分为新列?
【发布时间】:2019-01-06 06:40:38
【问题描述】:

所以我在 pandas 中有一个包含许多列的数据框。

一列有一个列表,其中包含用 [u'str',] 分隔的字符串,如下所示。每行中的字符串数量不相等。

column x
[u'str1', u'str2', u'str3']
[u'str4', u'str1']
[u'str5', u'str7', u'str8', u'str9']

我想在名为 column x-1, column x-2 up to x-n 的数据框中创建新列

我该怎么做:

  1. 算出我需要多少新列(即最大列表有多少成员?)
  2. 使用提到的命名法创建那么多列。
  3. 最重要的是:将字符串拆分为新的列,只保留单引号之间的内容(即丢失 u、' 和逗号)

【问题讨论】:

标签: python pandas dataframe split


【解决方案1】:

所以这个问题的确切代码是:

df_test['actors_list'] = df_m.actors_list.str.split('u\'') #splits based on deliminator u' (the \ is the escape character)
df_test2 = pd.DataFrame(
    df_test['actors_list'].tolist()).rename(lambda x: 'actors_list-{}'.format(x + 1), axis=1)
df_test2

【讨论】:

    【解决方案2】:

    如果 "column x" 是列表的列,您可以将该列作为 Series 传递以创建新的 DataFrame。

    df['column x']
    0    [a, b, c]
    1          [d]
    2       [e, f]
    dtype: object
    
    df2 = pd.DataFrame(
        df['column x'].tolist()).rename(lambda x: 'x-{}'.format(x + 1), axis=1)
    df2
    
      x-1   x-2   x-3
    0   a     b     c
    1   d  None  None
    2   e     f  None
    

    要将这些列添加回df,请使用pd.concat

    df = pd.concat([df, df2, axis=1])
    

    【讨论】:

    • 我得到错误'dict'对象没有属性'format'
    • @Sharkfan1781110 请复制代码而不是输入代码。您没有正确输入。
    • 好的,这样错误就消失了,但现在它仍然在一列中。我们在哪里定义分隔符?
    • @Sharkfan1781110 运行df['column x'].head(5) 并在您的问题中发布输出,否则我无能为力。
    • 从原帖中记住 u'str3' 需要转到 str3
    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2017-04-04
    • 2022-12-21
    • 1970-01-01
    • 2021-12-02
    • 2014-03-14
    相关资源
    最近更新 更多