Number Logic
Number Logic

Reputation: 894

adding a column to a pandas dataframe using a dictionary

I want to add columns to an existing dataframe based on a dictionary. If my dataframe looks like:

import pandas as pd
column_names=['name','surname','age']
lfa=[("tom","jones",44),("elvis","prestley",50),("jim","reeves",30)]
lfa=pd.DataFrame(lfa,columns=column_names)
lfa

and my dictionary looks like:

new_cols= {"adj1":"adjustment1","adj2":"adjustment2"}

then, I am trying to get a dataframe that looks like:

column_names=['name','surname','age','adj1','adj2']
lfa=[("tom","jones",44,"adjustment1","adjustment2"), 
("elvis","prestley",50,"adjustment1","adjustment2"), 
("jim","reeves",30,"adjustment1","adjustment2")]
lfa=pd.DataFrame(lfa,columns=column_names)
lfa

Upvotes: 1

Views: 93

Answers (4)

Mayank Porwal
Mayank Porwal

Reputation: 34046

One way could be using pd.concat:

In [533]: df = pd.concat([lfa, pd.DataFrame(new_cols, index=lfa.index)], 1)

In [534]: df
Out[534]: 
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

Upvotes: 1

Anurag Dabas
Anurag Dabas

Reputation: 24304

You can also do this by:-

lfa[list(new_cols.keys())]=new_cols.values()

print(lfa)
    name    surname     age     adj1        adj2
0   tom     jones       44  adjustment1     adjustment2
1   elvis   prestley    50  adjustment1     adjustment2
2   jim     reeves      30  adjustment1     adjustment2

Upvotes: 1

theairbend3r
theairbend3r

Reputation: 799

You can run a loop on dictionary key-value pairs and add them to you dataframe.

for key,value in new_cols.items():
    lfa[key] = value

Upvotes: 0

jezrael
jezrael

Reputation: 862406

Use DataFrame.assign with unpack dict by **:

df = lfa.assign(**new_cols)
print (df)
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

Or DataFrame.join:

df = lfa.join(pd.DataFrame(new_cols, index=lfa.index))
print (df)
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

Upvotes: 4

Related Questions