代码之家  ›  专栏  ›  技术社区  ›  msh855

当函数从r到python

  •  3
  • msh855  · 技术社区  · 7 年前

    如何在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
    

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

    if age < 10 then baby
     if age >= 10 and age < 20 then kid 
    if age >=20 and age < 30 then young 
    if age >= 30 and age < 50 then mature 
    if age >= 50 then grandpa 
    

    有人能帮忙吗?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Alex    7 年前

    你想用 np.select :

    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 choices 列表的长度必须相同。