我有以下資料框

import pandas as pd
import numpy as np
df = pd.DataFrame({
"Country": ["A", "A", "A", "A", "B", "B", "B", "B"],
"Year": [2020, 2020, 2021, 2021, 2020, 2020, 2021, 2021],
"Category": [1, 2, 1, 2, 1, 2, 1, 2],
"Count": [np.nan, np.nan, 1, 2, 3, np.nan, 5, 6]
})
我想洗掉Country與Yearcolumn共享值并NaN在 column 中有值的所有值Count。所以在這種情況下,行 id 0 和 1 將被洗掉(注意第 5 行不應該被洗掉)。
這可以通過一些內置的 pandas 功能在不回圈的情況下實作嗎?
下面的代碼達到了預期的效果,但是效率很低(真實的資料框要大得多):
for country in df.Country.unique():
for year in df.Year.unique():
if df[(df.Country==country) & (df.Year==year)].Count.isna().all():
df.drop(df[(df.Country==country) & (df.Year==year)].index, inplace=True)
有沒有更好、更有效的方法?
uj5u.com熱心網友回復:
您可以使用groupbyandfilter僅保留“并非每個計數都為空”的組。
import pandas as pd
import numpy as np
df = pd.DataFrame({
"Country": ["A", "A", "A", "A", "B", "B", "B", "B"],
"Year": [2020, 2020, 2021, 2021, 2020, 2020, 2021, 2021],
"Category": [1, 2, 1, 2, 1, 2, 1, 2],
"Count": [np.nan, np.nan, 1, 2, 3, np.nan, 5, 6]
})
df.groupby(['Country','Year']).filter(lambda x: ~x['Count'].isnull().all())
輸出
Country Year Category Count
2 A 2021 1 1.0
3 A 2021 2 2.0
4 B 2020 1 3.0
5 B 2020 2 NaN
6 B 2021 1 5.0
7 B 2021 2 6.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417955.html
標籤:
