如何将 Pandas 中的一列扩展为多列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42920363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:14:43  来源:igfitidea点击:

How to expand one column in Pandas to many columns?

pythonpandasscikit-learnbigdata

提问by Liu Chong

As the title, I have one column (series) in pandas, and each row of it is a list like [0,1,2,3,4,5]. Each list has 6 numbers. I want to change this column into 6 columns, for example, the [0,1,2,3,4,5]will become 6 columns, with 0is the first column, 1is the second, 2is the third and so on. How can I make it?

作为标题,我在 Pandas 中有一个列(系列),它的每一行都是一个像[0,1,2,3,4,5]. 每个列表有 6 个数字。我想把这一列改成6列,比如[0,1,2,3,4,5]将变成6列,有0第一列,1第二列,2第三列等等。我怎样才能做到?

回答by piRSquared

Not as fast as @jezrael's solution. But elegant :-)

不如@jezrael 的解决方案快。但优雅:-)

applywith pd.Series

applypd.Series

df.a.apply(pd.Series)

   0  1  2  3  4  5
0  0  1  2  3  4  5
1  0  1  2  3  4  5

or

或者

df.a.apply(pd.Series, index=list('abcdef'))

   a  b  c  d  e  f
0  0  1  2  3  4  5
1  0  1  2  3  4  5

回答by jezrael

You can convert lists to numpy arrayby valuesand then use DataFrameconstructor:

您可以将列表转换为numpy arraybyvalues然后使用DataFrame构造函数:

df = pd.DataFrame({'a':[[0,1,2,3,4,5],[0,1,2,3,4,5]]})
print (df)
                    a
0  [0, 1, 2, 3, 4, 5]
1  [0, 1, 2, 3, 4, 5]

df1 = pd.DataFrame(df['a'].values.tolist())
print (df1)
   0  1  2  3  4  5
0  0  1  2  3  4  5
1  0  1  2  3  4  5


cols = list('abcdef')
df1 = pd.DataFrame(df['a'].values.tolist(), columns=cols)
print (df1)
   a  b  c  d  e  f
0  0  1  2  3  4  5
1  0  1  2  3  4  5

回答by Heavy Breathing

If I understood your question correctly, you are looking for a transpose operation.

如果我正确理解了您的问题,那么您正在寻找转置操作。

df = pd.DataFrame([1,2,3,4,5],columns='a')
# .T stands for transpose
print(df.T)