如何将 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
How to expand one column in Pandas to many columns?
提问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 0
is the first column, 1
is the second, 2
is 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 的解决方案快。但优雅:-)
apply
with pd.Series
apply
和 pd.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 array
by values
and then use DataFrame
constructor:
您可以将列表转换为numpy array
byvalues
然后使用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)