0

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?

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • What is the issue, exactly? Have you tried anything, done any research? Stack Overflow is not a free code writing service. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Mar 11 '20 at 23:18
  • Does this answer your question? [pandas - add new column to dataframe from dictionary](https://stackoverflow.com/questions/29794959/pandas-add-new-column-to-dataframe-from-dictionary) – AMC Mar 11 '20 at 23:20
  • The first part of the question is an exact duplicate of the one above, as for the second part it is trivial. – AMC Mar 11 '20 at 23:21

3 Answers3

5
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.

Ben Pap
  • 2,549
  • 1
  • 8
  • 17
1

Try:

df['c']=df['State'].map(stateC)
df['d']=df['b'].astype(int).div(df['c'])
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
1

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
Shadab Hussain
  • 794
  • 6
  • 24