Home > Software engineering >  Appending thousands of columns of a dictionary to an existing dataframe
Appending thousands of columns of a dictionary to an existing dataframe

Time:12-09

I have a dictionary that has entries like this

res = {L1:[1,2,3,4], L2:[5,6,7,8]......Ln:[9,10,11,12]}

and a Pandas dataframe (df) like this

Item Code
A     ac 
B     bd
C     ef 
D     jk

I want to merge these two data structures in such a way that the final outcome will be like this

Item Code  L1  L2.....Ln
A     ac    1   5     9
B     bd    2   6     10
C     ef    3   7     11
D     jk    4   8     12

This is what I have tried so far

meta_df = pd.DataFrame({'ITEM': df['ITEM'],'CODE': df['CODE']})
for i in [x for x in range(1, 1000):
     L_df = pd.Dataframe({'L{}'.format(i):res['L{}'.format(i)]})    

transformed_df = pd.concat([meta_df, L_df], axis=1) 

But this does not work, the data is misaligned in the transformed_df

CodePudding user response:

Try with assign

out = df.assign(**res)
  • Related