给定一些数据,例如
pd.DataFrame(list('SxxxxxxxxESxxxxESxxxxxxxxxxxxE'))
如何将其分成以“S”开头并以“E”结尾的 block ?
真实的数据当然更复杂,有一列包含如上所述的数据,而其他列我想使用groupby
。
最终目标是能够检索并处理所有符合其他列标准的 S/E 分隔 block (例如,给定执行此操作的神话函数 group_chunks
,myData. groupby('Person').group_chunks().Value.sum()
).
更新
响应对更真实的数据和所需输出的请求,数据如下所示:
df = pd.DataFrame({'PID': [1]*12+[2]*6,
'Cond': ['A']*6+['B']*6+['A']*6,
'Flag': ['START', 'DOWN', 'MOVE', 'MOVE', 'LIFT', 'END']*3,
'Value': np.random.random(18)})
Cond Flag PID Value
0 A START 1 0.156338
1 A DOWN 1 0.706541
2 A MOVE 1 0.569177
3 A MOVE 1 0.308874
4 A LIFT 1 0.150780
5 A END 1 0.553462
6 B START 1 0.028738
7 B DOWN 1 0.512303
8 B MOVE 1 0.975988
9 B MOVE 1 0.735695
10 B LIFT 1 0.094430
11 B END 1 0.467895
12 A START 2 0.114679
13 A DOWN 2 0.911095
14 A MOVE 2 0.359117
15 A MOVE 2 0.819148
16 A LIFT 2 0.505313
17 A END 2 0.874462
因此,使用神秘的 group_chunks
(并记住 START
和 END
之间的行数并不总是相同),我想要做类似的事情
df.groupBy('PID').group_chunks('Flag', 'START', 'END').Value.sum()
得到类似的结果
Cond PID Value.sum
0 A 1 2.445172
1 B 1 2.347153
2 A 2 3.583813
最佳答案
这是一个使用 numpy 的选项。它至少应该让您朝着正确的方向开始。为了方便和可读性,我将您的专栏命名为“SE”:
df = pd.DataFrame(list('SxxxxxxxxESxxxxESxxxxxxxxxxxxE'), columns=['SE'])
split_points = np.where(df['SE'] == 'E')[0] + 1 # array of after-"E" indices
found = np.array_split(df['data'], split_points) # split series
found = found[:-1] # remove the empty series at the end of the list
关于python - Pandas 按开始/结束值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40732694/