将 lambda 与 pandas 一起使用以计算以现有列为条件的新列

我需要在 pandas DataFrame 中创建一个新列,该列计算为 DataFrame 中 2 个现有列的比率。但是,比率计算中的分母将根据在 DataFrame 的另一列中找到的字符串值而变化。

例子。示例数据集:

import pandas as pd
df = pd.DataFrame(data={'hand'      : ['left','left','both','both'], 
                        'exp_force' : [25,28,82,84], 
                        'left_max'  : [38,38,38,38], 
                        'both_max'  : [90,90,90,90]})

我需要df['ratio']根据 的条件创建一个新的 DataFrame 列df['hand']

如果df['hand']=='left'那么df['ratio'] = df['exp_force'] / df['left_max']

如果df['hand']=='both'那么df['ratio'] = df['exp_force'] / df['both_max']


Smart猫小萌
浏览 128回答 3
3回答

收到一只叮咚

您可以使用np.where():import pandas as pddf = pd.DataFrame(data={'hand'      : ['left','left','both','both'],                         'exp_force' : [25,28,82,84],                         'left_max'  : [38,38,38,38],                         'both_max'  : [90,90,90,90]})df['ratio'] = np.where((df['hand']=='left'), df['exp_force'] / df['left_max'], df['exp_force'] / df['both_max'])dfOut[42]:    hand  exp_force  left_max  both_max     ratio0  left         25        38        90  0.6578951  left         28        38        90  0.7368422  both         82        38        90  0.9111113  both         84        38        90  0.933333或者,在现实生活中,如果您有很多条件和结果,那么您可以使用np.select(),这样您就不必np.where()像我在旧代码中所做的那样不断重复您的语句。最好np.select在这些情况下使用:import pandas as pddf = pd.DataFrame(data={'hand'      : ['left','left','both','both'],                         'exp_force' : [25,28,82,84],                         'left_max'  : [38,38,38,38],                         'both_max'  : [90,90,90,90]})c1 = (df['hand']=='left')c2 = (df['hand']=='both')r1 = df['exp_force'] / df['left_max']r2 = df['exp_force'] / df['both_max']conditions = [c1,c2]results = [r1,r2]df['ratio'] = np.select(conditions,results)dfOut[430]:    hand  exp_force  left_max  both_max     ratio0  left         25        38        90  0.6578951  left         28        38        90  0.7368422  both         82        38        90  0.9111113  both         84        38        90  0.933333

素胚勾勒不出你

枚举for i,e in enumerate(df['hand']):   if e == 'left':    df.at[i,'ratio'] = df.at[i,'exp_force'] / df.at[i,'left_max']  if e == 'both':    df.at[i,'ratio'] = df.at[i,'exp_force'] / df.at[i,'both_max']df输出:    hand    exp_force   left_max    both_max    ratio0   left    25            38          90      0.6578951   left    28            38          90      0.7368422   both    82            38          90      0.9111113   both    84            38          90      0.933333

慕的地6264312

您可以使用apply()数据框的方法:df['ratio'] = df.apply(    lambda x: x['exp_force'] / x['left_max'] if x['hand']=='left' else x['exp_force'] / x['both_max'],    axis=1)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python