我有一個資料框 df,我想在其中根據季度填充特定列中的缺失值。
資料
type date stat test
aa Q1 2022 20 1
aa Q2 2022 10 2
aa Q3 2022 30 1
bb Q1 2022 30 1
bb Q2 2022 10 1
期望的
type date stat test
aa Q1 2022 20 1
aa Q2 2022 10 2
aa Q3 2022 30 1
aa Q4 2022 0
bb Q1 2022 30 1
bb Q2 2022 10 1
bb Q3 2022 0
bb Q4 2022 0
正在做
Logic:
The pattern is Q1 2022, Q2 2022, Q3 2022 and Q4 2022.
If there is a 'break' in this pattern, the missing data should fill in accordingly with a stat
value of 0.
我相信我可以創建一個字典,然后結合 impute 函式
data = { "Q1 2022":0 ,
"Q2 2022":0 ,
"Q3 2022":0 ,
"Q4 2022":0 ,
}
df["type"].fillna("", inplace = True)
df["date"].fillna("", inplace = True) #input dictionary mapping
df["stat"].fillna("0", inplace = True)
任何建議表示贊賞。
uj5u.com熱心網友回復:
你可以pivot先后reindex退
l =['Q1 2022','Q2 2022','Q3 2022','Q4 2022']
out = df.pivot(*df).reindex(columns = l,fill_value=0).stack().reset_index(name = 'stat')
uj5u.com熱心網友回復:
創建一個包含所有組合的新資料框,type然后dates將其與原始資料框合并。最后,根據您的規則填充值:
from itertools import product
dates = ['Q1 2022', 'Q2 2022', 'Q3 2022', 'Q4 2022']
df1 = pd.DataFrame(product(df['type'].unique(), dates), columns=['type', 'date'])
df1 = df1.merge(df, how='left').fillna({'stat': 0, 'test': ''})
輸出:
>>> df1
type date stat test
0 aa Q1 2022 20.0 1.0
1 aa Q2 2022 10.0 2.0
2 aa Q3 2022 30.0 1.0
3 aa Q4 2022 0.0
4 bb Q1 2022 30.0 1.0
5 bb Q2 2022 10.0 1.0
6 bb Q3 2022 0.0
7 bb Q4 2022 0.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416479.html
標籤:
