如何在Pandas中将列表拼接成数据帧

6
c1=["q","q","q","q","q","q"]
c2=["x","x","x","x","x","x"]
c3=["w","w","w","w","w","w"]
ca=["c","e","a","d"]
cb=["y","z","s","f"]
cc=["y","z","s","f"]
df1=pd.DataFrame(c1, columns=['c1'])
df2=pd.DataFrame(c2, columns=['c2'])
df3=pd.DataFrame(c3, columns=['c3'])
df4=pd.DataFrame(ca, columns=['ca'])
df5=pd.DataFrame(cb, columns=['cb'])
df6=pd.DataFrame(cc, columns=['cc'])
df7=pd.concat([df1,df2,df3,df4,df5,df6],axis=1)
df7

我想做的是连接列表(长度不同)并创建数据框。我尝试使用zip(),但无法实现。有什么更简单的方法吗?
1个回答

4

您可以将一系列数据作为concat的参数而不是一系列数据框。使用字典来处理变量数量不确定的情况是一个好主意,这样可以将未来的列名存储在键中。

d = {'c1': c1, 'c2': c2, 'c3': c3, 'ca': ca, 'cb': cb, 'cc': cc}

df = pd.concat([pd.Series(v, name=k) for k, v in d.items()], axis=1)

print(df)

  c1 c2 c3   ca   cb   cc
0  q  x  w    c    y    y
1  q  x  w    e    z    z
2  q  x  w    a    s    s
3  q  x  w    d    f    f
4  q  x  w  NaN  NaN  NaN
5  q  x  w  NaN  NaN  NaN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接