gpt4 book ai didi

python - 填写每组行的数据框值

转载 作者:行者123 更新时间:2023-11-28 20:31:14 25 4
gpt4 key购买 nike

假设我有以下数据集:

Time    Geography           Sex     Population
1990 Northern Ireland Male NA
1990 Northern Ireland Female NA
1990 Northern Ireland Total NA
1991 Northern Ireland Male NA
1991 Northern Ireland Female NA
1991 Northern Ireland Total NA
1992 Northern Ireland Male 792100
1992 Northern Ireland Female 831100
1992 Northern Ireland Total 1623300
1993 Northern Ireland Male 812100
1993 Northern Ireland Female 851100
1993 Northern Ireland Total 1663200

最后我想要的是:

Time    Geography           Sex     Population
1990 Northern Ireland Male 792100
1990 Northern Ireland Female 831100
1990 Northern Ireland Total 1623300
1991 Northern Ireland Male 792100
1991 Northern Ireland Female 831100
1991 Northern Ireland Total 1623300
1992 Northern Ireland Male 792100
1992 Northern Ireland Female 831100
1992 Northern Ireland Total 1623300
1993 Northern Ireland Male 812100
1993 Northern Ireland Female 851100
1993 Northern Ireland Total 1663200

这意味着基本上我想用没有 NA 的第一年的值填充前几年的值。

我该怎么做?

最佳答案

你可以链pandas.DataFrame.sort_values , pandas.DataFrame.fillna使用方法 bfill 然后是 pandas.DataFrame.sort_index按顺序恢复原始索引:

df = df.sort_values(['Sex']).fillna(method='bfill').sort_index()

print(df)
Time Geography Sex Population
0 1990 Northern Ireland Male 792100.0
1 1990 Northern Ireland Female 831100.0
2 1990 Northern Ireland Total 1623300.0
3 1991 Northern Ireland Male 792100.0
4 1991 Northern Ireland Female 831100.0
5 1991 Northern Ireland Total 1623300.0
6 1992 Northern Ireland Male 792100.0
7 1992 Northern Ireland Female 831100.0
8 1992 Northern Ireland Total 1623300.0

关于python - 填写每组行的数据框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326084/

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