当每个列表的成员数可能不同时,如何将列表中的一列拆分为新列?

2024-06-28 18:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

一列有一个列表,其中的字符串以[u'str',]结尾,如下所示。每行中的字符串数目不相等。在

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

我想在dataframe中创建新的列,称为column x-1,column x-2直到x-n

如何:

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

attempted code


Tags: 数据字符串pandas列表结尾columnstr数目
2条回答

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

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

如果“column x”是列表的列,则可以将该列作为一个序列传递,以创建新的数据帧。在

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

^{pr2}$

相关问题 更多 >