函数从R到Python时的大小写

2024-09-27 21:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python代码中实现R的case-when函数?在

当R的函数为:

https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/case_when

作为最低限度的工作示例,假设我们有以下数据帧(python代码如下所示):

import pandas as pd
import numpy as np

data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
        'age': [42, 52, 36, 24, 73], 
        'preTestScore': [4, 24, 31, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70]}
df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore', 'postTestScore'])
df

假设我们要创建一个名为“老年人”的新列,该列查看“年龄”列并执行以下操作:

^{pr2}$

有人能帮忙吗?在


Tags: 函数代码namehttpsimportdfagedata
1条回答
网友
1楼 · 发布于 2024-09-27 21:28:31

您要使用^{}

conditions = [(df['age'].lt(10)), 
              (df['age'].ge(10) & df['age'].lt(20)), 
              (df['age'].ge(20) & df['age'].lt(30)), 
              (df['age'].ge(30) & df['age'].lt(50)), 
              (df['age'].ge(50))]
choices = ['baby', 'kid', 'young', 'mature', 'grandpa']

df['elderly'] = np.select(conditions, choices)

df
    name  age  preTestScore  postTestScore  elderly
0  Jason   42             4             25   mature
1  Molly   52            24             94  grandpa
2   Tina   36            31             57   mature
3   Jake   24             2             62    young
4    Amy   73             3             70  grandpa

conditions和{}列表的长度必须相同。在

相关问题 更多 >

    热门问题