【发布时间】:2020-03-17 11:55:24
【问题描述】:
给定以下数据:
x1 = 'one'
x2 = 'two'
x3 = 'three'
y1 = 'yes'
y2 = 'no'
n = 3
df = pd.DataFrame(dict(
a = [x1]*n + [x2]*n + [x3]*n,
b = [
y1,
y1,
y2,
y2,
y2,
y2,
y2,
y2,
y1,
]
))
看起来像:
Out[5]:
a b
0 one yes
1 one yes
2 one no
3 two no
4 two no
5 two no
6 three no
7 three no
8 three yes
我想知道是否可以按如下方式创建列c:
Out[5]:
a b c
0 one yes 1
1 one yes 1
2 one no 1
3 two no 0
4 two no 0
5 two no 0
6 three no 1
7 three no 1
8 three yes 1
如果a 中的组b 包含yes,则c 被定义为1
我尝试了以下方法:
group_results = df.groupby('a').apply(lambda x: 'yes' in x.b.to_list() )
group_results = group_results.reset_index()
group_results = group_results.rename(columns = {0 : 'c'})
df = pd.merge(df, group_results, left_on = 'a',
right_on = 'a',
how = 'left').copy()
但我觉得好像有更好的方法。
【问题讨论】:
标签: python pandas conditional-statements grouping