这是我的数据框:
import pandas as pd
df = pd.DataFrame(
{
'a': ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'z', 'z', 'z', 'p', 'p', 'p', 'p'],
'b': [1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1]
}
)
这就是预期的输出。我想创建专栏
c
:
a b c
0 x 1 first
1 x -1 first
2 x 1 first
3 x 1 first
4 y -1 second
5 y 1 second
6 y 1 second
7 y -1 second
11 p 1 first
12 p 1 first
13 p 1 first
14 p 1 first
组由
a
列定义。我想过滤 df
并选择第一个 b
为 1 或第二个 b
为 1 的组。
我通过这段代码做到了这一点:
df1 = df.groupby('a').filter(lambda x: (x.b.iloc[0] == 1) | (x.b.iloc[1] == 1))
并且为了为
c
创建列 df1
,再次应通过 a
定义组,然后如果每个组第一个 b
为 1,则 c
为 first
,如果第二个 b
为1 那么 c
就是 second
。
请注意,对于组
p
,第一个和第二个 b
都是 1,对于这些组,我希望 c
为 first
。
也许我处理问题的方式是完全错误的。
代码
g = df.groupby(['a'])['b']
df['c'] = (df['a'].map(g.nth(0)[lambda x: x.eq(1)].replace(1, 'first'))
.fillna(
df['a'].map(g.nth(1)[lambda x: x.eq(1)].replace(1, 'second'))
)
)
df
a b c
0 x 1 first
1 x -1 first
2 x 1 first
3 x 1 first
4 y -1 second
5 y 1 second
6 y 1 second
7 y -1 second
8 z -1 NaN
9 z -1 NaN
10 z -1 NaN
11 p 1 first
12 p 1 first
13 p 1 first
14 p 1 first
过滤器:
out = df[df['c'].notna()]