【发布时间】:2019-07-06 07:02:03
【问题描述】:
如何在 python 代码中实现 R 的 case_when 函数?
这里是 R 的 case_when 函数:
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
假设我们想要创建一个名为“elderly”的新列,它查看“age”列并执行以下操作:
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
有人可以帮忙吗?
【问题讨论】:
标签: python pandas dataframe data-analysis