twinturbotom
twinturbotom

Reputation: 1544

pandas columns from another DataFrame if value is in another column?

I have pd.DataFrame listing wire gauges and their corresponding currents:

e_ref =

   wire_gauge  current
0          14       15
1          12       20
2          10       30
3           8       50
4           6       60
5           4       85
6           3      100
7           2      115

Another DataFrame lists breakers in a system:

system =

    breakers
0         30
1         20
2         30
3         15
4         30

I need to add a "wire gauge" column to the system DataFrame from the "wire_gauge" columns of the e_ref DataFrame by looking up the breaker value in the current series of the e_ref.

so the output would be:

    breakers  wire_gauge
0         30  10
1         20  12
2         30  10
3         15  14
4         30  10

I keep confusing several answers from other post and currently do not have a working pandas solution. I can get this working using python loops but I feel like there is a pandas one liner here...

Below are the types of solutions I'm working on:

df.ix[df.breakers.isin(e_ref['current']), 'wire_gauge'] = e_ref['wire_gauge']

and

df['wire_gauge']=e_ref.loc[e_ref['current'] == df['breakers'] ]

Thanks for your time and direction!

Upvotes: 1

Views: 1718

Answers (1)

jezrael
jezrael

Reputation: 862521

Use map by Series created form e_ref or join, but is necessary values in currentcolumn in e_ref has to be unique:

print (e_ref['current'].is_unique)
True

s = e_ref.set_index('current')['wire_gauge']
system['wire_gauge'] = system['breakers'].map(s)
print (system)
   breakers  wire_gauge
0        30          10
1        20          12
2        30          10
3        15          14
4        30          10

Alternative:

df = system.join(e_ref.set_index('current'), on='breakers')
print (df)
   breakers  wire_gauge
0        30          10
1        20          12
2        30          10
3        15          14
4        30          10

Upvotes: 2

Related Questions