我找不到where不起作用的原因,但有一个办法:
创建代码以创建df:def make_row():
import random
dico = {"MOSL_Rating" : ['Highly Effective', 'Effective', 'Ineffective', 'Developing'],
"MOTP_Rating" : ['Developing', 'Ineffective', 'Highly Effective', 'Effective', 'Highly Effective'],
"disp_rating" : range(100)}
row = {}
for k in dico.keys():
v = random.choice(dico[k])
row[k] =v
return row
def make_df(nb_row):
import pandas as pd
rows = [make_row() for i in range(nb_row)]
return pd.DataFrame(rows)
我可以创建df:
^{pr2}$
还有第二个:df2 = make_df(3)
df2
MOSL_Rating MOTP_Rating disp_rating
0 Effective Highly Effective 24
1 Effective Developing 38
2 Highly Effective Ineffective 16
然后我创建您的测试:MOSL_high_efective = df['MOSL_Rating'] == 'Highly Effective'
MOSL_efective = df['MOSL_Rating'] == 'Effective'
MOSL_inefective = df['MOSL_Rating'] == 'Ineffective'
MOSL_developing = df['MOSL_Rating'] == 'Developing'
MOTP_high_efective = df['MOTP_Rating'] == 'Highly Effective'
MOTP_efective = df['MOTP_Rating'] == 'Effective'
MOTP_inefective = df['MOTP_Rating'] == 'Ineffective'
MOTP_developing = df['MOTP_Rating'] == 'Developing'
test1 = MOSL_high_efective & MOTP_developing
test2 = MOSL_high_efective & MOTP_inefective
test3 = MOSL_efective & MOTP_inefective
test4 = MOSL_inefective & MOTP_high_efective
test5 = MOSL_inefective & MOTP_efective
test6 = MOSL_developing & MOTP_high_efective
conditions = test1 | test2 | test3 | test4 | test5 | test6
然后在满足条件的情况下,用第二个数据帧更新第一个数据帧的值:lines_to_be_updates = df.loc[conditions].index.values
df.loc[lines_to_be_updates, "disp_rating"] = df2[lines_to_be_updates]["disp_rating"]
df
MOSL_Rating MOTP_Rating disp_rating
0 Highly Effective Ineffective 24
1 Highly Effective Highly Effective 71
2 Effective Ineffective 16