将不同长度的列表附加到数据框熊猫

时间:2020-04-25 08:49:45

标签: pandas dataframe

考虑到我有多个列表

A = ['acc_num=1', 'A1', 'A2']
B = ['acc_num=2', 'B1', 'B2', 'B3','B4']
C = ['acc_num=3', 'C1']

如何将它们放入数据框以导出为ex​​cel:

   acc_num     _1  _2  _3  _4  
_1 1           A1  A2
_2 2           B1  B2  B3  B4
_3 3           C1

1 个答案:

答案 0 :(得分:0)

您好,以下3个基本步骤为您提供了解决方案:

  1. 仅通过传递列表列表即可创建DataFrame
  2. 操纵acc_num列并删除起始字符串"acc_num=",这是通过在向量化列上使用字符串方法来完成的(但到目前为止可能还很远)
  3. 通过将字典{}传递给df.rename
  4. ,根据需要重命名列标题/名称。

代码:

# Create a Dataframe from your lists
df = pd.DataFrame([A,B,C])
# Change Column 0 and remove initial string
df[0] = df[0].str.replace('acc_num=','')
# Change the name of Column 0
df.rename(columns={0:"acc_num"},inplace=True)

最终结果:

Out[26]: 
  acc_num   1     2     3     4
0       1  A1    A2  None  None
1       2  B1    B2    B3    B4
2       3  C1  None  None  None