pandas“应用”中的问题替换缺失值的函数

发布于 2025-01-11 16:25:10 字数 676 浏览 3 评论 0原文

我想使用“apply”函数将 np.nan 值替换为 pandas.DataFrame 中的其他值。我将使用 replace 方法,其中 NaN 被替换为每列的最大值(axis=0)。下面你就更好理解了。

import pandas as pd

df = pd.DataFrame({'a':[1, np.nan, 3],
                  'b':[np.nan,5,6],
                  'c':[7,8,np.nan]})

result = df.apply(lambda c: c.replace(np.nan, max(c)), axis=0)
print(result)

共有三个 np.nan 值。其中两个被替换为适当的值,但只有一个值仍然是 np.nan(下图)

在此处输入图像描述

将参数 axis 设置为 <代码>1,仍有一个值未被替换。原因是什么?

I want to replace np.nan values with other value in pandas.DataFrame using 'apply' function. And I will use replace method that where NaN is replaced with max value of each column (axis=0). You better understand below.

import pandas as pd

df = pd.DataFrame({'a':[1, np.nan, 3],
                  'b':[np.nan,5,6],
                  'c':[7,8,np.nan]})

result = df.apply(lambda c: c.replace(np.nan, max(c)), axis=0)
print(result)

There are three np.nan values. Two of them is replaced with appropriate values, but just one value is still np.nan(below picture)

enter image description here

After setting argument axis to 1, there is still one value that isn't replaced. What's the reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2025-01-18 16:25:11

如果列表以 NaN 开头,Python 的 max 将不起作用;因此 max(df['b']) 返回 NaN 并且无法填充该列中的 NaN 值。使用 c.max() (它可以工作,因为默认情况下 Series.max 会跳过 NaN)。所以:

df = df.apply(lambda c: c.replace(np.nan, c.max()), axis=0)

但是您可以在轴上使用 fillna,而不是 replace

df = df.fillna(df.max(), axis=0)

输出:

     a    b    c
0  1.0  6.0  7.0
1  3.0  5.0  8.0
2  3.0  6.0  8.0

Python's max doesn't work if a list starts with NaN; so max(df['b'])returns NaN and it cannot fill the NaN value in that column. Use c.max() instead (which works because by default Series.max skips NaNs). So:

df = df.apply(lambda c: c.replace(np.nan, c.max()), axis=0)

But instead of replace, you could use fillna on axis:

df = df.fillna(df.max(), axis=0)

Output:

     a    b    c
0  1.0  6.0  7.0
1  3.0  5.0  8.0
2  3.0  6.0  8.0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文