如何基于值对 Pandas Series 进行分区?

4

我有一个类似下面的DF:

>>> df
        order_received
0            1
1            1
2            0
3            0
4            1
5            0
6            0 

我想把这个分成(1), (1), (0, 0, 1), (0, 0),即每当出现1时就分割系列。我该怎么做?

1个回答

5
您可以使用cumsum对列进行反向排序,然后使用groupby+list
df.groupby(df.order_received.iloc[::-1].eq(1).cumsum())['order_received'].apply(list).iloc[::-1]
Out[419]: 
order_received
3          [1]
2          [1]
1    [0, 0, 1]
0       [0, 0]
Name: order_received, dtype: object

第二种方法是使用shift加上cumsum

df.groupby(df.order_received.shift().fillna(0).cumsum())['order_received'].apply(list)
Out[432]: 
order_received
0.0          [1]
1.0          [1]
2.0    [0, 0, 1]
3.0       [0, 0]
Name: order_received, dtype: object

1
这可以不用 .eq() :) - An SO User
@LittleChild 是的,你说得对 :-) ,以防万一你有一些检查器而不是1。 - BENY

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