Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas add multiple new columns at once from list of lists

I have a list of timestamp lists where each inner list looks like this:

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

Is it possible with Pandas to add five new columns at the same time to an already created dataframe (same length as the outer list), that are equal to each of these values, with names 'day','month','date','time','year'?

like image 588
Austin Avatar asked Mar 09 '23 10:03

Austin


1 Answers

I think you can use DataFrame constructor with 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

One liner:

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
like image 196
jezrael Avatar answered Apr 29 '23 15:04

jezrael