给出以下数据:
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
其中c
定义为1
如果a
该列b
中的组包含yes
我尝试了以下方法:
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()
但是我觉得似乎有更好的方法。
使用Series.isin
的测试组与至少一个yes
在a
列,最后转换面具与整数Series.view
:
df['c'] = df['a'].isin(df.loc[df['b'].eq('yes'), 'a']).view('i1')
print(df)
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
详细说明:
print(df.loc[df['b'].eq('yes'), 'a'])
0 one
1 one
8 three
Name: a, dtype: obje
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句