gpt4 book ai didi

python - Pandas 数据框 : Replacing NaN with row average

转载 作者:太空狗 更新时间:2023-10-29 17:10:55 24 4
gpt4 key购买 nike

我正在尝试学习 Pandas ,但我一直对以下内容感到困惑。我想用行平均值替换 DataFrame 中的 NaN。因此,像 df.fillna(df.mean(axis=1)) 这样的东西应该可以工作,但由于某种原因它对我来说失败了。我错过了什么,我在做什么有问题吗?是因为没有实现吗?见link here

import pandas as pd
import numpy as np

pd.__version__
Out[44]:
'0.15.2'

In [45]:
df = pd.DataFrame()
df['c1'] = [1, 2, 3]
df['c2'] = [4, 5, 6]
df['c3'] = [7, np.nan, 9]
df

Out[45]:
c1 c2 c3
0 1 4 7
1 2 5 NaN
2 3 6 9

In [46]:
df.fillna(df.mean(axis=1))

Out[46]:
c1 c2 c3
0 1 4 7
1 2 5 NaN
2 3 6 9

但是这样的东西看起来工作正常

df.fillna(df.mean(axis=0)) 

Out[47]:
c1 c2 c3
0 1 4 7
1 2 5 8
2 3 6 9

最佳答案

正如评论的那样,fillna 的轴参数是 NotImplemented .

df.fillna(df.mean(axis=1), axis=1)

注意:这在这里很重要,因为您不想用第 n 行的平均值填充第 n 列。

现在您需要迭代:

m = df.mean(axis=1)
for i, col in enumerate(df):
# using i allows for duplicate columns
# inplace *may* not always work here, so IMO the next line is preferred
# df.iloc[:, i].fillna(m, inplace=True)
df.iloc[:, i] = df.iloc[:, i].fillna(m)

print(df)

c1 c2 c3
0 1 4 7.0
1 2 5 3.5
2 3 6 9.0

另一种方法是填充转置然后转置,这可能更有效......

df.T.fillna(df.mean(axis=1)).T

关于python - Pandas 数据框 : Replacing NaN with row average,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058590/

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