Change the pandas DataFrame column value based on a different column value

I have a dataframe with two columns, each of which represents an organism. They are called ORG1 and ORG2. I want to move the values ​​of ORG2 to ORG1 for the corresponding index value.

So, if ORG1 is β€œA” and ORG2 is β€œB”, I want ORG1 to take the value β€œB” from ORG2.

I have already begun work on identifying the indexes of ORG2 organisms that I want to move as follows:

def move_org2(x): org2_matches = Series(x.ORG2.str.count("ESBL")) return x.ix[org2_matches == 1] org2_DF = move_org2(DF) org2_DF.ORG2.index 

What is the best way to use this to change ORG1 values ​​with the corresponding ORG2 index values

+6
python pandas dataframe
source share
2 answers
 In [13]: df Out[13]: ORG1 ORG2 0 A ESBL 1 BP 2 CQ 3 DR 4 E ESBL In [14]: cond = df.ORG2 == 'ESBL' In [15]: df.ORG1[cond] = df.ORG2[cond] In [16]: df Out[16]: ORG1 ORG2 0 ESBL ESBL 1 BP 2 CQ 3 DR 4 ESBL ESBL 
+15
source share

In other words, using .loc you would do

 In [2008]: df Out[2008]: ORG1 ORG2 0 A ESBL 1 BP 2 CQ 3 DR 4 E ESBL In [2009]: df.loc[df['ORG2'] == 'ESBL', 'ORG1'] = df['ORG2'] In [2010]: df Out[2010]: ORG1 ORG2 0 ESBL ESBL 1 BP 2 CQ 3 DR 4 ESBL ESBL 

Or, if you need a copy, without changing the original df , you can use .mask()

 In [2016]: df.mask(df['ORG2'] == 'ESBL', df['ORG2'], axis=0) Out[2016]: ORG1 ORG2 0 ESBL ESBL 1 BP 2 CQ 3 DR 4 ESBL ESBL 
+2
source share

All Articles