[英]Python (pandas) - How to group values in one column and then delete or keep that group based on values in another column
[英]Pandas group by but keep another column
假設我有一個看起來像這樣的數據框
date location year
0 1908-09-17 Fort Myer, Virginia 1908
1 1909-09-07 Juvisy-sur-Orge, France 1909
2 1912-07-12 Atlantic City, New Jersey 1912
3 1913-08-06 Victoria, British Columbia, Canada 1912
我想使用 pandas groupby 函數來創建一個輸出,該輸出顯示每年的事件總數,但同時保留將顯示當年位置之一的位置列。 任何一個工作。 所以它看起來像這樣:
total location
year
1908 1 Fort Myer, Virginia
1909 1 Juvisy-sur-Orge, France
1912 2 Atlantic City, New Jersey
這可以在不進行時髦加入的情況下完成嗎? 我能得到的最遠的是使用普通的 groupby
df = df.groupby(['year']).count()
但這只會給我這樣的東西
location
year
1908 1 1
1909 1 1
1912 2 2
如何顯示此數據框中的位置之一?
您可以使用groupby.agg
並使用'first'
來提取每個組中的第一個位置:
res = df.groupby('year')['location'].agg(['first', 'count'])
print(res)
# first count
# year
# 1908 Fort Myer, Virginia 1
# 1909 Juvisy-sur-Orge, France 1
# 1912 Atlantic City, New Jersey 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.