Pandas 从列表列表中一次添加多个新列

Posted

技术标签:

【中文标题】Pandas 从列表列表中一次添加多个新列【英文标题】:Pandas add multiple new columns at once from list of lists 【发布时间】:2017-08-29 02:45:43 【问题描述】:

我有一个时间戳列表,其中每个内部列表如下所示:

['Tue', 'Feb', '7', '10:07:40', '2017']

Pandas 是否可以同时向已创建的数据框(与外部列表长度相同)添加五个新列,它们等于每个值,名称为 'day','month','date','time','year'

【问题讨论】:

【参考方案1】:

我认为您可以将DataFrame 构造函数与concat 一起使用:

df = pd.DataFrame('A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9])

L = [['Tue', 'Feb', '7', '10:07:40', '2017'],
     ['Tue', 'Feb', '7', '10:07:40', '2017'],
     ['Tue', 'Feb', '7', '10:07:40', '2017']]

cols = ['day','month','date','time','year']
df1 = pd.DataFrame(L, columns=cols)
print (df1)
   day month date      time  year
0  Tue   Feb    7  10:07:40  2017
1  Tue   Feb    7  10:07:40  2017
2  Tue   Feb    7  10:07:40  2017

df2 = pd.concat([df, df1], axis=1)
print (df2)
   A  B  C  day month date      time  year
0  1  4  7  Tue   Feb    7  10:07:40  2017
1  2  5  8  Tue   Feb    7  10:07:40  2017
2  3  6  9  Tue   Feb    7  10:07:40  2017

一个班轮:

df2 = pd.concat([df, pd.DataFrame(L, columns=['day','month','date','time','year'])], axis=1)
print (df2)
   A  B  C  day month date      time  year
0  1  4  7  Tue   Feb    7  10:07:40  2017
1  2  5  8  Tue   Feb    7  10:07:40  2017
2  3  6  9  Tue   Feb    7  10:07:40  2017

【讨论】:

以上是关于Pandas 从列表列表中一次添加多个新列的主要内容,如果未能解决你的问题,请参考以下文章