Number Logic
Number Logic

Reputation: 894

concatenating a dictionary to a dataframe with conditions

I am trying to concatenate a dictionary to a dataframe. When the dictionary has keys that are already in the dataframe, I am trying to delimit the values. Otherwise, I create a new column.

So, the original dataframe looks like:

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

and the dictionary looks like:

new_cols= {"desc1":"adjustment1","desc3":"adjustment3"}

I am trying to create an output that looks like:

column_names=['name','surname','age','desc1','desc2','desc3']
lfa=[("tom","jones",44,"d1|adjustment1","d2","adjustment3"), 
("elvis","prestley",50,"d1|adjustment1","d2","adjustment3"), 
("jim","reeves",30,"d1|adjustment1","d2","adjustment3")]
lfa=pd.DataFrame(lfa,columns=column_names)
lfa

Upvotes: 1

Views: 44

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71689

for-loop

Loop over dict items and update/add the columns in the dataframe

for k, v in new_cols.items():
    lfa[k] = lfa[k] + '|' + v if k in lfa else v

    name   surname  age           desc1 desc2        desc3
0    tom     jones   44  d1|adjustment1    d2  adjustment3
1  elvis  prestley   50  d1|adjustment1    d2  adjustment3
2    jim    reeves   30  d1|adjustment1    d2  adjustment3

Upvotes: 3

Related Questions