2 回答

TA貢獻1887條經驗 獲得超5個贊
您可以從 year 列中的唯一值創建最近幾年的列表,并使用布爾索引來使用該列表索引數據框。
recent_years = df.Year.unique()[-3:]
df[df.Year.isin(recent_years)]
Country Year Value
3 Israel 2001 2.8
4 Denmark 2001 1.1
5 Israel 2002 2.9
6 Congo 2002 3.1
7 Israel 2003 1.9
8 Congo 2003 3.0
9 Denmark 2003 3.1
如果您的 Year 值不一定按順序排列,請使用 numpy unique 返回排序數組,這與 pandas unique() 不同
recent_years = np.unique(df.Year)[-3:]
df[df.Year.isin(recent_years)]
這是另一個解決方案,它為每個國家/地區返回 3 個最近的年份。如果數據沒有按年份排序,則需要先排序。
idx = df.groupby('Country').apply(lambda x: x['Year'].tail(3)).index
df.set_index(['Country', df.index]).reindex(idx).reset_index().drop('level_1', 1)
Country Year Value
0 Congo 2000 1.2
1 Congo 2002 3.1
2 Congo 2003 3.0
3 Denmark 2000 3.1
4 Denmark 2001 1.1
5 Denmark 2003 3.1
6 Israel 2001 2.8
7 Israel 2002 2.9
8 Israel 2003 1.9
如果數據沒有排序,首先使用排序
df = df.sort_values(by = 'Year')

TA貢獻1884條經驗 獲得超4個贊
這是我使用 Pandas 的解決方案。即使它使用了很多行代碼,它也完成了它必須做的事情。感謝@Vaishali 的幫助:
threshold = 3 #Anything that occurs less than this will be removed,
#if it ocurrs more, the extra ocurrences with the least values
#will be removed.
newIndex = df.set_index('Country')#set new index to make selection by
#index posible.
values = newIndex.index.value_counts() #Count occurrences of index values.
to_keep = values[values>=threshold].index.values
#Keep index values that ocurr >= threshold.
rank_df = newIndex.loc[to_keep,['Value','Year']]#Select rows and
#columns to keep.
#Sort values in descending order before meeting threshold.
rank_df = rank_df.sort_values('Value',ascending=False)
rank_df = rank_df.groupby(rank_df.index).head(threshold)#group again
#Since values are sorted, head() will show highest values
rank_df = rank_df.groupby([rank_df.index,'Year']).mean() \
.sort_values('Value',ascending=False)
#Finally, reset index to convert Year index into a column, and sort by year
rank_df.reset_index(level=1).sort_values('Year')
輸出:
Year Value
Country
Denmark 2000 3.1
Israel 2000 2.5
Congo 2000 1.2
Israel 2001 2.8
Denmark 2001 1.1
Congo 2002 3.1
Israel 2002 2.9
Denmark 2003 3.1
Congo 2003 3.0
添加回答
舉報