How to expand one column in Pandas to many columns?

倖福魔咒の 提交于 2019-11-28 08:54:11

问题


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?


回答1:


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

apply with 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



回答2:


You can convert lists to numpy array by values and then use DataFrame constructor:

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



回答3:


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)


来源:https://stackoverflow.com/questions/42920363/how-to-expand-one-column-in-pandas-to-many-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!