亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

選擇一個數據框的子集,每個變量都有 N 年的數據

選擇一個數據框的子集,每個變量都有 N 年的數據

素胚勾勒不出你 2021-11-02 20:06:48
我有一個數據集,顯示了 100 多個國家的年度增長指標,從 1970 年到 2013 年。并非所有國家都有所有年份的數據,年份最少的國家擁有 30 年的數據。我想把事情弄平,讓所有國家向我展示 30 年的數據,從超過 30 年的國家中刪除年份。我在下面提供了一個例子。我想過使用循環從數據框中刪除數據,直到所有國家/地區都出現 30 次,然后構建一個全新的數據框,但我相信有更好的解決方案。import pandas as pddata = {'Country':['Israel','Congo','Denmark',                   'Israel','Denmark',                   'Israel','Congo',                   'Israel','Congo','Denmark'],        'Year':[2000,2000,2000,                2001,2001,                2002,2002,                2003,2003,2003],        'Value':[2.5,1.2,3.1,2.8,1.1,2.9,3.1,1.9,3.0,3.1]}df = pd.DataFrame(data=data)df   Country  Year  Value0   Israel  2000    2.51    Congo  2000    1.22  Denmark  2000    3.13   Israel  2001    2.84  Denmark  2001    1.15   Israel  2002    2.96    Congo  2002    3.17   Israel  2003    1.98    Congo  2003    3.09  Denmark  2003    3.1上面的代碼使用僅使用 3 個國家和 4 年的示例創建了一個數據框。從數據框中,您可以看到以色列有 4 年的數據,而丹麥和剛果只有三年。我想從以色列刪除一年,以便所有國家都有 3 年。在實際數據框中,我想從超過 30 年的國家中刪除年份,以便所有國家/地區都具有相同的年份,最好刪除價值最小的年份。這是我使用 for 循環的解決方案,它使用了很多代碼行:gp = df.groupby('Country').groups #Group by country named = {} #Build dictionary Country Name => index list.for i in gp: #Iterate over all countries until a list of 3 indeces is #reached for each country.    d[i] = []    for j in gp[i]:        if len(d[i])<3: #A country appears once every year in the dataset,#3 means 3 years. If a country appears more than 3 times, it will only #include the indices of the first 3 occurrences.             d[i].append(j)indeces = [] #Gather the indeces to keep in the dataframe.for i in d:    for j in d[i]:        if len(d[i])==3: #make sure the list has exactly 3 items            indeces.append(j)
查看完整描述

2 回答

?
慕工程0101907

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')


查看完整回答
反對 回復 2021-11-02
?
慕村9548890

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


查看完整回答
反對 回復 2021-11-02
  • 2 回答
  • 0 關注
  • 209 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號