gpt4 book ai didi

python - 根据 Python 中的模式填充缺失的列值

转载 作者:行者123 更新时间:2023-12-05 02:34:27 24 4
gpt4 key购买 nike

我有一个数据框 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.

我相信我可以创建一个字典,然后结合插补函数

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)

如有任何建议,我们将不胜感激。

最佳答案

你可以先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')

关于python - 根据 Python 中的模式填充缺失的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70764397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com