【发布时间】:2020-08-22 08:59:23
【问题描述】:
我需要在 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['hand']的条件新建一个DataFrame列df['ratio']。
如果df['hand']=='left' 那么df['ratio'] = df['exp_force'] / df['left_max']
如果df['hand']=='both' 那么df['ratio'] = df['exp_force'] / df['both_max']
【问题讨论】:
-
np.where(df.hand.eq('left'), df['exp_force'] / df['left_max'], df['exp_force'] / df['both_max'])
标签: python pandas dataframe lambda