Kunal Puranik
Kunal Puranik

Reputation: 35

How to create a new column in a Pandas DataFrame based on a column in another DataFrame?

*I am new to Python and Pandas
I need to do the following
I have 2 DataFrames, lets call them df1 and df2

df1

Index    Req ID  City_Atlanta   City_Seattle    City_Boston Result  
 0        X         1                0            0           0  
 1        Y         0                1            0           0  
 2        Z         0                0            1           1

df2

Index    Req_ID    City        
  0         X      Atlanta     
  1         Y      Seattle     
  2         Z      Boston    

I want to add a column in df2 called result such that df2.result = False if df1.result = 0 and df2.result = True if df1.result = 1

The final result should look like df2

Index    Req_ID    City       result 
  0         X      Atlanta     False
  1         Y      Seattle     False
  2         Z      Boston      True

I am new to asking question on Stack Overflow as well so pardon any common mistakes.

Upvotes: 0

Views: 50

Answers (3)

anky
anky

Reputation: 75080

Considering Req ID is the matching key and the length of the dfs are not the same, you can use:

df2['Result'] = df2.Req_ID.map(dict(zip(df['Req ID'],df.Result))).astype(bool)

0    False
1    False
2     True

If lengths are equal you can use the above sol by @aws_apprentice

Upvotes: 3

gold_cy
gold_cy

Reputation: 14216

You can apply a bool to the 0,1's.

df2['Result'] = df1['Result'].apply(bool)

You can also map a dictionary of values.

df2['Result'] = df1['Result'].map({0: False, 1: True})

Upvotes: 2

Dallas Lindauer
Dallas Lindauer

Reputation: 239

Assuming they're the same lengths you can do:

df2['Result'] = df1['Result']==1

Upvotes: 1

Related Questions