gpt4 book ai didi

python - 有没有办法获得 pandas 中前两列的平均值?

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:35 25 4
gpt4 key购买 nike

我想计算前两行的平均值并将 NAN 填充到我的数据框中。 2010-19 列中只有几行缺少值。

我尝试使用 bfillffill 但它只捕获上一个或下一个行/列值并填充 NAN。

我的示例数据集有 7 列,如下所示:

X       1990-2000   2000-2010   2010-19   1990-2000  2000-2010   2010-19
Hyderabad 10 20 NAN 1 3 NAN

我想要的输出:

X          1990-2000   2000-2010   2010-19   1990-2000  2000-2010   2010-19
Hyderabad 10 20 15 1 3 2

最佳答案

使用fillna以这种方式,一个简单的解决方案是提供 pandas 系列作为 fillna 的参数。这将根据索引替换 NaN 值。

由于列名称重复,因此以下代码使用列索引。假设一个名为 df 的数据帧:

col_indices = [3, 6]

for i in col_indices:
means = df.iloc[:, [i-1, i-2]].mean(axis=1)
df.iloc[:, i].fillna(means, inplace=True)

这将使用 col_indices 中每列左侧两列的平均值填充 NaN 值。

关于python - 有没有办法获得 pandas 中前两列的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55986653/

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