使用不同寻常的方式对pandas数据框进行分组

15

问题

我有以下 Pandas dataframe:

    data = {
        'ID':  [100, 100, 100, 100, 200, 200, 200, 200, 200, 300, 300, 300, 300, 300],
        'value': [False, False, True, False, False, True, True, True, False, False, False, True, True, False],
    }
    df = pandas.DataFrame (data, columns = ['ID','value'])

我想获取以下分组:

  • 分组1:对于每个ID,获取该ID的第一个True行之前的所有False行
  • 分组2:对于每个ID,获取该ID的最后一个True行之后的所有False行
  • 分组3:所有True行

enter image description here

可以使用Pandas完成吗?

我的尝试

我尝试过:

group = df.groupby((df['value'].shift() != df['value']).cumsum())

但是这会返回一个不正确的结果。


1
  • 组1:对于每个ID,取该ID的第一个True行之前的所有False行。
  • 组2:对于每个ID,取该ID的最后一个True行之后的所有False行。
  • 组3:所有True行。
- Ford1892
你在 True 之间是否曾经出现过 False - Quang Hoang
3个回答

9

让我们尝试使用 shift + cumsum 创建分组键:顺便说一下,我真的很喜欢您显示的期望输出方式。

s = df.groupby('ID')['value'].apply(lambda x : x.ne(x.shift()).cumsum())
d = {x : y for x ,y in df.groupby(s)}
d[2]
     ID  value
2   100   True
5   200   True
6   200   True
7   200   True
11  300   True
12  300   True
d[1]
     ID  value
0   100  False
1   100  False
4   200  False
9   300  False
10  300  False
d[3]
     ID  value
3   100  False
8   200  False
13  300  False

2

让我们尝试按照您的逻辑来做:

# 1. all False up to first True
group1 = df.loc[df.groupby('ID')['value'].cumsum() == 0]

# 2. all False after last True
group2 = df.loc[df.iloc[::-1].groupby('ID')['value'].cumsum()==0]

# 3. all True
group3 = df[df['value']]

输出:

    ID      value
0   100     False
1   100     False
4   200     False
9   300     False
10  300     False

    ID      value
3   100     False
8   200     False
13  300     False

    ID      value
2   100     True
5   200     True
6   200     True
7   200     True
11  300     True
12  300     True

1
这适用于您的示例数据。
df['groups'] = df.groupby('ID').value.apply(lambda x: x.diff().ne(False).cumsum()).astype('int')
for _,df_groups in df.groupby('groups'):
  print(df_groups)
  print('-'*20)

输出:
     ID  value  groups
0   100  False       1
1   100  False       1
4   200  False       1
9   300  False       1
10  300  False       1
--------------------
     ID  value  groups
2   100   True       2
5   200   True       2
6   200   True       2
7   200   True       2
11  300   True       2
12  300   True       2
--------------------
     ID  value  groups
3   100  False       3
8   200  False       3
13  300  False       3
--------------------

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接