python lambda if elif_使用pandas的IF和ELIF功能-问答-阿里云开发者社区-阿里云

我知道你的问题特别要求一个将数据帧作为参数的函数,但我觉得你的方法破坏了数据帧的强度。我会选择直接转型方法

import pandas as pd

df = pd.read_csv('your_data_source.csv')

Function output in a new column fn_A

df['fn_A'] = df[df['A'].apply(lambda x: x < 125)]['A'].apply(lambda y: 935 + 0.2 * y)

df['fn_A'] = df[df['A'].apply(lambda x: 955 < x < 974)]['A'].apply(lambda y: 921.2 + 0.2 * (y - 955))

df['fn_A'] = df[df['A'].apply(lambda x: 975 < x < 1023)]['BCCH'].apply(lambda y: 925.2 + 0.2 * (y - 975))

df['fn_A'] = df[df['A'].apply(lambda x: 511 < x < 885)]['A'].apply(lambda y: 1805.2 + 0.2 * (y - 512))

您可以利用它np.select来管理您的条件和选项。这使您可以轻松地维护您的条件和选项,并使用numpy库函数,这可能有助于加快您的代码

def fn(dframe):

import numpy as np

condlist = [

dframe['A'] < 125,

(dframe['A'] >= 955) and (dframe['A'] <= 974),

(dframe['A'] >= 975) and (dframe['A'] <= 1023),

(dframe['A'] >= 511) and (dframe['A'] <= 885),

]

choicelist = [

935 + 0.2 * dframe['A'],

921.2 + 0.2 * (dframe['A'] - 955),

925.2 + 0.2 * (dframe['BCCH'] - 975),

1805.2 + 0.2 * (dframe['A'] - 512),

]

output = np.select(condlist,choicelist)

return output

看来你需要np.where

import numpy as np

np.where(dframe['A'] < 125, 935 + 0.2 * dframe['A'],

np.where(dframe['A'] >= 511) & (dframe['A'] <= 885), 1805.2 + 0.2 * (dframe['A'] - 512,

np.where(dframe['A'] <= 974, 921.2 + 0.2 * (dframe['A'] - 955),

np.where(dframe['A'] <= 1023, 925.2 + 0.2 * (dframe['A'] - 975),

'Value for any other value'))))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值