[英]Change a pandas DataFrame column value based on another 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 into ORG1 for the corresponding index value. 它们被称为ORG1和ORG2我想将ORG2的值移动到ORG1中以获得相应的索引值。
So, if ORG1 is 'A' and ORG2 is 'B' I want ORG1 to take the value 'B' from ORG2. 因此,如果ORG1为'A'且ORG2为'B',我希望ORG1从ORG2获取值'B'。
I have already started work to identify indexes of the ORG2 organisms that I want to move, as follows: 我已经开始确定我要移动的ORG2生物的索引,如下所示:
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 values at corresponding ORG2 indices 使用它来更改ORG1值与相应ORG2索引值的最佳方法是什么
In [13]: df
Out[13]:
ORG1 ORG2
0 A ESBL
1 B P
2 C Q
3 D R
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 B P
2 C Q
3 D R
4 ESBL ESBL
In other words, using .loc
you would do 换句话说,使用.loc
就可以了
In [2008]: df
Out[2008]:
ORG1 ORG2
0 A ESBL
1 B P
2 C Q
3 D R
4 E ESBL
In [2009]: df.loc[df['ORG2'] == 'ESBL', 'ORG1'] = df['ORG2']
In [2010]: df
Out[2010]:
ORG1 ORG2
0 ESBL ESBL
1 B P
2 C Q
3 D R
4 ESBL ESBL
Or, if you need a copy, without modifying original df
, you can use .mask()
或者,如果您需要副本而不修改原始df
,则可以使用.mask()
In [2016]: df.mask(df['ORG2'] == 'ESBL', df['ORG2'], axis=0)
Out[2016]:
ORG1 ORG2
0 ESBL ESBL
1 B P
2 C Q
3 D R
4 ESBL ESBL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.