Reputation: 3
I have two dataframes,
df1 =
Countries description | Continents | values |
---|---|---|
C0001 also called America, | America | 21tr |
C0004 and C0003 are neighbhors | Europe | 504 bn |
on advancing C0005 with C0001.security | Europe | 600bn |
C0002, the smallest continent | Australi | 1.7tr |
df2 =
Countries | Id |
---|---|
US | C0001 |
Australia | C0002 |
Finland | C0003 |
Norway | C0004 |
Japan | C0005 |
df1 has columns Countries descriptions but instead of their actual names, codes are given. df2 has countries with their codes.
I want to replace the countries Code(like C0001, C0002) with their Names in the df1, like this:
df1 =
Countries description | Continents | values |
---|---|---|
US also called America, some.. | America | 21tr |
Norway and Finland are neighbhors | Europe | 504 bn |
on advancing Japan with US.security | Europe | 600bn |
Australia, the smallest continent | Austral | 1.7tr |
I tried with the Pandas merge method but that didnt work:
df3 = df1.merge(df2, on=['Countries'], how='left')
Thanks :)
Upvotes: 0
Views: 39
Reputation: 37787
Here is one way to approach it with replace
:
d = dict(zip(df2["Id"], df2["Countries"]))
df1["Countries description"] = df1["Countries description"].replace(d, regex=True)
Output :
print(df1)
Countries description Continents values
0 US also called America, America 21tr
1 Norway and Finland are neighbhors Europe 504 bn
2 on advancing Japan with US.security Europe 600bn
3 Australia, the smallest continent Australi 1.7tr
Upvotes: 1