I have two data frames in which one column is common. I want to compare both the data frames and map the value of the 2nd column in data frame 2 to the first if matched properly. For example, I have one data frame say treasury_shares with column entity_Id another data frame say soiValues with columns entityId and attribute_value. I want to compare the entity_Id and create a new column in data frame A with attribute_value values properly assigned to entity_Id in the data frame treasury_shares as they were in data frame soiValues.
Currently what I am doing is treasury_shares.insert(6, "SOI priority",soiValues['attribute_value'], True)
I am only inserting the attribute_value values as it is what I get from the database in the form of data frame soiValues. But the SOI priority values are assigned in an improper manner in the data frame treasury_shared to the respective entity IDs with my approach. Wrong attribute_value values are been assigned.
Can anyone help me in building the logic for this? Will the below code work?
for index, row in treasury_shares.iterrows():
for index,row in soiValues.iterrows():
if (treasury_shares['entity_id']==soiValues['entity_id']):
treasury_shares['SOI priority']=soiValues['attribute_value']
You should check out merge
function in Pandas library
A quick demo for the same -
import pandas as pd
lst = [['A', 1], ['B', 2],
['C', 3], ['D', 4]]
df1 = pd.DataFrame(lst, columns =['x1', 'x2'])
lst2 = [['A', 'Hello'], ['B', 'Hola'],
['C', 'Hi'], ['D', 'Hey']]
df2 = pd.DataFrame(lst, columns =['x1', 'x3'])
df1.merge(df2,on='x1',how='left')
If there are values of x1
in df1
with no corresponding values in df2
you will get a row with NaN
in x3
column
If there are values of x1
in df2
with no corresponding values in df1
it will not show up in the output currently but can be added by tinkering with the 'how'
parameter
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.