python当中df的用法_使用np.哪里根据条件在pandas df中创建新列

我找不到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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值