[英]Select last observation per group
有人要求在pandas df中選擇每組的第一個觀察值,我對第一個和最后一個都感興趣,除了編寫for循環之外,我不知道這樣做的有效方法。
我將修改他的例子來告訴你我在找什么基本上有一個 df 像這樣:
group_id
1
1
1
2
2
2
3
3
3
我想要一個變量來指示組中的最后一次觀察:
group_id indicator
1 0
1 0
1 1
2 0
2 0
2 1
3 0
3 0
3 1
首先,我們將創建一個包含每個組的最后一個元素的索引位置列表。 您可以看到每個組的元素如下:
>>> df.groupby('group_id').groups
{1: [0, 1, 2], 2: [3, 4, 5], 3: [6, 7, 8]}
我們使用列表推導來提取每個組索引值的最后一個索引位置 ( idx[-1]
)。
我們通過使用列表推導式和三元運算符(即 1 if condition else 0)將指標分配給數據幀,遍歷索引中的每個元素並檢查它是否在idx_last_group
列表中。
idx_last_group = [idx[-1] for idx in df.groupby('group_id').groups.values()]
df['indicator'] = [1 if idx in idx_last_group else 0 for idx in df.index]
>>> df
group_id indicator
0 1 0
1 1 0
2 1 1
3 2 0
4 2 0
5 2 1
6 3 0
7 3 0
8 3 1
使用pandas.shift
,您可以執行以下操作:
df['group_indicator'] = df.group_id != df.group_id.shift(-1)
(或者
df['group_indicator'] = (df.group_id != df.group_id.shift(-1)).astype(int)
如果將它作為整數對您來說實際上很重要。)
筆記:
對於大型數據集,這應該比列表理解(更不用說循環)快得多。
正如 Alexander 所指出的,這假設 DataFrame 已按示例中的方式排序。
您可以groupby
的“ID”和呼叫nth(-1)
以獲得各組的最后一個條目,然后用它來掩蓋DF和“指標”設置為1
與再剩下的0
使用fillna
:
In [21]:
df.loc[df.groupby('group_id')['group_id'].nth(-1).index,'indicator'] = 1
df['indicator'].fillna(0, inplace=True)
df
Out[21]:
group_id indicator
0 1 0
1 1 0
2 1 1
3 2 0
4 2 0
5 2 1
6 3 0
7 3 0
8 3 1
這是groupby
的輸出:
In [22]:
df.groupby('group_id')['group_id'].nth(-1)
Out[22]:
2 1
5 2
8 3
Name: group_id, dtype: int64
一條線:
data['indicator'] = (data.groupby('group_id').cumcount()==data.groupby('group_id')['any_other_column'].transform('size') -1 ).astype(int)`
我們要做的是檢查累積計數(返回與數據幀大小相同的向量)是否等於我們使用變換計算的“組大小 - 1”,因此它也返回與數據幀大小相同的向量.
我們需要使用其他一些列進行轉換,因為它不會讓您轉換.groupby()
變量,但這實際上可以轉換任何其他列,並且不會受到影響,因為它僅用於計算新指標。 使用.astype(int)
使其成為二進制文件並完成。
使用.tail
方法:
df=df.groupby('group_id').tail(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.