Pandas DataFrame:如何组合连续值我在DataFrame中有一个包含值的列:[1, 1, -1, 1, -1, -1]我该如何将它们分组呢?[1,1] [-1] [1] [-1, -1]
2 回答

慕桂英4014372
TA贡献1871条经验 获得超13个赞
您可以groupby按自定义使用Series:
df = pd.DataFrame({'a': [1, 1, -1, 1, -1, -1]})
print (df)
a
0 1
1 1
2 -1
3 1
4 -1
5 -1
print ((df.a != df.a.shift()).cumsum())
0 1
1 1
2 2
3 3
4 4
5 4
Name: a, dtype: int32
for i, g in df.groupby([(df.a != df.a.shift()).cumsum()]):
print (i)
print (g)
print (g.a.tolist())
a
0 1
1 1
[1, 1]
2
a
2 -1
[-1]
3
a
3 1
[1]
4
a
4 -1
5 -1
[-1, -1]

慕的地6264312
TA贡献1817条经验 获得超6个赞
使用groupby
从itertools
来自杰斯数据
from itertools import groupby[ list(group) for key, group in groupby(df.a.values.tolist())]Out[361]: [[1, 1], [-1], [1], [-1, -1]]
添加回答
举报
0/150
提交
取消