Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas df append new column based on dict

I was trying to add a new column in my dataframe, by using a dictionary:

my dataframe looks like this:

df = pd.DataFrame({
        'Time': [1,2,3,4,5,6,7,8,9,10],
        'Code': ['A', 'C', 'X', 'Y', 'A', 'B', 'X', 'A', 'Z', 'L'],
        'Value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        })

and my dic looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dic = {(1,'A',1):"P",(2,'C',2):"O",(3,'X',3):"P",(4,'Y',4):"O",(5,'A',5):"P",(6,'B',6):"O",(7,'X',7):"P",(8,'A',8):"P",(9,'Z',9):"O",(10,'L',10):"O"}

I did some research on how to do this and come up with using map function:

df['final'] = dic[df['Time',"Code","Value"].map(dic)

But it does work – unhashable type: "Series" ..

Is there any way to solve this? Thanks guys

>Solution :

Use DataFrame.join with convert dic to Series:

df = df.join(pd.Series(dic).rename('final'), on=['Time','Code','Value'])
print (df)
   Time Code  Value final
0     1    A      1     P
1     2    C      2     O
2     3    X      3     P
3     4    Y      4     O
4     5    A      5     P
5     6    B      6     O
6     7    X      7     P
7     8    A      8     P
8     9    Z      9     O
9    10    L     10     O
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading