edgarmtze
edgarmtze

Reputation: 25058

How to add value to a pandas dataframe column by row depending a key value in a dictionary?

I have a dictionary with a value c for states

stateC =    {
  "Washington" : 3,
  "New York" :  5,
  "Houston":  11,
}

and a dataframe:

State       b    
Washington  09   
New York    100    
Houston     55   

I would like to integrate that column based on key value of dictionary in column c and also a column d that has value in b/c

State       b    c   d
Washington  09   3   3
New York    100  5   20  
Houston     55   11  5

How to do that in pandas?

Upvotes: 0

Views: 887

Answers (3)

Shadab Hussain
Shadab Hussain

Reputation: 814

Try this code:

df['c'] = df['State'].apply(lambda x: stateC[x]) 
df['d'] = df[['b','c']].apply(lambda x: x[0]//x[1], axis=1)
df

Upvotes: 1

Georgina Skibinski
Georgina Skibinski

Reputation: 13407

Try:

df['c']=df['State'].map(stateC)
df['d']=df['b'].astype(int).div(df['c'])

Upvotes: 1

Ben Pap
Ben Pap

Reputation: 2579

df['c'] = df['State'].map(stateC)
df['d'] = df['b']/df['c']

You can create a new column that is identical to the State column, then map the dict. Column d is pretty self explanatory.

Upvotes: 5

Related Questions