python - 使用 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']
根据df['hand']
.
如果df['hand']=='left'
那时df['ratio'] = df['exp_force'] / df['left_max']
如果df['hand']=='both'
那时df['ratio'] = df['exp_force'] / df['both_max']
解决方案
您可以使用np.where()
:
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'] = np.where((df['hand']=='left'), df['exp_force'] / df['left_max'], df['exp_force'] / df['both_max'])
df
Out[42]:
hand exp_force left_max both_max ratio
0 left 25 38 90 0.657895
1 left 28 38 90 0.736842
2 both 82 38 90 0.911111
3 both 84 38 90 0.933333
或者,在现实生活场景中,如果您有很多条件和结果,那么您可以使用np.select()
,这样您就不必np.where()
像我在旧代码中所做的那样不断重复您的陈述。最好np.select
在这些情况下使用:
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]})
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)
df
Out[430]:
hand exp_force left_max both_max ratio
0 left 25 38 90 0.657895
1 left 28 38 90 0.736842
2 both 82 38 90 0.911111
3 both 84 38 90 0.933333
推荐阅读
- reactjs - 切换到 TypeScript 后的依赖问题
- python-3.x - 碰撞点是否有等效的颜色功能?
- mongodb - 如何在codeigniter中用“like”查询MongoDB?
- c# - DbContext 作为控制器构造函数中的依赖注入
- android - 卸载应用程序时,我不希望删除 SqlLite 数据库
- regex - 检查字符串中的引号,即数字后跟逗号
- php - 我想将 jQuery 代码导入 WordPress 产品页面和 functions.php 文件
- sql - 在sql server中将多行转换为包含数据的列
- java - Hibernate JPA 2 Metamodel Generator土耳其字符问题
- android - 片段中的 TabLayout 显示空白的白条