Reputation: 793
I've two dataframes df & df1
and i've converted the df1
to a dictionary as it contains only two columns. As shown below:
import pandas as pandas
df = pd.read_csv('data.csv')
df['company'] = 0
df1 = pd.read_csv('data1.csv')
mydict = dict(zip(df1.agent_id, df1.company))
for x in df.agent_id:
for k,v in mydict.items():
if k == x:
df.loc[df['company']] = v
Now i want to append the value of mydict
as a value in column df['company']
if it fulfils the following conditions. How can i do this? can somebody explain? I know i'm just missing a simple logic. I can't figure it out though.
ifdf
is this
agent_id
0 184
1 182
2 113
3 157
4 137
5 199
6 181
and mydict
is this:
mydict = {184: 'LuxuryPods',
113: 'smartflat.com',
157: 'ApartaMinutes',
199: 'HouseMouse',
181: 'LuxuryPods',
182: 'Ramax',
137: 'LuxuryPods'}
then the resultant df
should look like this:
agent_id company
0 184 LuxuryPods
1 182 Ramax
2 113 smartflat.com
3 157 ApartaMinutes
4 137 LuxuryPods
5 199 HouseMouse
6 181 LuxuryPods
Upvotes: 0
Views: 2197
Reputation: 1035
try the following code
df = pd.DataFrame({'agent_id': [184, 182, 113, 157]})
mydict = {184: 'LuxuryPods',
113: 'smartflat.com',
157: 'ApartaMinutes',
182: 'Ramax'}
df['company'] = df['agent_id'].map(mydict)
Output
agent_id company
0 184 LuxuryPods
1 182 Ramax
2 113 smartflat.com
3 157 ApartaMinutes
The key is basically to use the map
function to map all values in agent_id
to their corresponding company. With the map
function, you can also specify what values you want, in the case where there's no match found. The argument is na_action
.
Upvotes: 3