我有一段時間(2001-2003 年)內許多國家的資料。它看起來像這樣:
| 指數 | 年 | 國家 | 通貨膨脹 | 國內生產總值 |
|---|---|---|---|---|
| 1 | 2001年 | AFG | 楠 | 48 |
| 2 | 2002年 | AFG | 楠 | 49 |
| 3 | 2003年 | AFG | 楠 | 50 |
| 4 | 2001年 | 氣 | 3.0 | 楠 |
| 5 | 2002年 | 氣 | 5.0 | 楠 |
| 6 | 2003年 | 氣 | 7.0 | 楠 |
| 7 | 2001年 | 美國 | 楠 | 220 |
| 8 | 2002年 | 美國 | 4.0 | 250 |
| 9 | 2003年 | 美國 | 2.5 | 280 |
如果任何給定變數都沒有資料(即所有年份的值都缺失),我想洗掉國家/地區。
在上面的示例表中,我想洗掉 AFG(因為它錯過了所有通貨膨脹值)和 CHI(GDP 缺失)。我不想僅僅因為缺少一年就放棄觀察#7。
最好的方法是什么?
uj5u.com熱心網友回復:
這應該通過過濾在(通貨膨脹,GDP)之一中具有 nan 的所有值來作業:
(
df.groupby(['country'])
.filter(lambda x: not x['inflation'].isnull().all() and not x['GDP'].isnull().all())
)
請注意,如果您有兩個以上的列,則可以使用更通用的版本:
df.groupby(['country']).filter(lambda x: not x.isnull().all().any())
如果您希望它使用特定的年份范圍而不是所有列,您可以設定一個掩碼并稍微更改代碼:
mask = (df['year'] >= 2002) & (df['year'] <= 2003) # mask of years
grp = df.groupby(['country']).filter(lambda x: not x[mask].isnull().all().any())
uj5u.com熱心網友回復:
你也可以試試這個:
# check where the sum is equal to 0 - means no values in the column for a specific country
group_by = df.groupby(['country']).agg({'inflation':sum, 'GDP':sum}).reset_index()
# extract only countries with information on both columns
indexes = group_by[ (group_by['GDP'] != 0) & ( group_by['inflation'] != 0) ].index
final_countries = list(group_by.loc[ group_by.index.isin(indexes), : ]['country'])
# keep the rows contains the countries
df = df.drop(df[~df.country.isin(final_countries)].index)
uj5u.com熱心網友回復:
您可以將資料框從長調整為寬,洗掉空值,然后再轉換回寬。
要從長轉換為寬,您可以使用資料透視函式。也看到這個問題。
這是重構后洗掉空值的代碼:
df.dropna(axis=0, how= 'any', thresh=None, subset=None, inplace=True) # Delete rows, where any value is null
要轉換回 long,您可以使用 pd.melt。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411439.html
標籤:
