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

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

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

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

【问题讨论】:

    标签: list pandas multiple-columns python-3.5


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多