我不小心用一个错误复制的链接关闭了这个问题.这是正确的:Pandas将列表列拆分为多列.
假设我有一个数据框,其中一列是一个列表(已知且相同的长度)或元组,例如:
df1 = pd.DataFrame(
{'vals': [['a', 'b', 'c', 'd'],['e','f','g','h']]}
)
Run Code Online (Sandbox Code Playgroud)
即:
vals
0 [a, b, c, d]
1 [e, f, g, h]
Run Code Online (Sandbox Code Playgroud)
我想将"vals"中的值添加到单独的命名列中.我可以通过遍历行来笨拙地做到这一点:
for i in range(df1.shape[0]):
for j in range(0,4):
df1.loc[i, 'vals_'+j] = df1.loc[i, 'vals'] [j]
Run Code Online (Sandbox Code Playgroud)
结果符合要求:
vals vals_0 vals_1 vals_2 vals_3
0 [a, b, c, d] a b c d
1 [e, f, g, h] e f g h
Run Code Online (Sandbox Code Playgroud)
有更整洁(矢量化)的方式吗?我尝试使用[]但是我收到了一个错误.
for j in range (0,4)
df1['vals_'+str(j)] = df1['vals'][j]
Run Code Online (Sandbox Code Playgroud)
得到:
ValueError: Length of values does not match length of index
Run Code Online (Sandbox Code Playgroud)
看起来Pandas试图将[]运算符应用于系列/数据帧而不是列内容.
您可以使用assign,apply与pd.Series:
df1.assign(**df1.vals.apply(pd.Series).add_prefix('val_'))
Run Code Online (Sandbox Code Playgroud)
更快的数据方法是使用.values和tolist()与数据帧构造函数:
df1.assign(**pd.DataFrame(df1.vals.values.tolist()).add_prefix('val_'))
Run Code Online (Sandbox Code Playgroud)
输出:
vals val_0 val_1 val_2 val_3
0 [a, b, c, d] a b c d
1 [e, f, g, h] e f g h
Run Code Online (Sandbox Code Playgroud)
您可以将Series初始化程序应用于vals,然后add_prefix获取您正在查找的列名称.然后concat到原始的所需输出:
pd.concat([df1.vals, df1.vals.apply(pd.Series).add_prefix("vals_")], axis=1)
vals vals_0 vals_1 vals_2 vals_3
0 [a, b, c, d] a b c d
1 [e, f, g, h] e f g h
Run Code Online (Sandbox Code Playgroud)