pandas“应用”中的问题替换缺失值的函数
我想使用“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)
After setting argument axis
to 1
, there is still one value that isn't replaced. What's the reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果列表以 NaN 开头,Python 的
max
将不起作用;因此max(df['b'])
返回NaN
并且无法填充该列中的 NaN 值。使用c.max()
(它可以工作,因为默认情况下Series.max
会跳过 NaN)。所以:但是您可以在轴上使用
fillna
,而不是replace
:输出:
Python's
max
doesn't work if a list starts with NaN; somax(df['b'])
returnsNaN
and it cannot fill the NaN value in that column. Usec.max()
instead (which works because by defaultSeries.max
skips NaNs). So:But instead of
replace
, you could usefillna
on axis:Output: