使用 fillna 在 Pandas 中使用列表填充空值 [英] Filling nulls with a list in Pandas using fillna
本文介绍了使用 fillna 在 Pandas 中使用列表填充空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个 pd.Series
,我想用一个列表替换空值.也就是说,给定:
Given a pd.Series
, I would like to replace null values with a list. That is, given:
import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])
我想要一个可以返回的函数
I want a function that would return
0 0
1 1
2 [nan]
但是如果我尝试为此使用自然函数,即 fillna
:
But if I try using the natural function for this, namely fillna
:
result = ser.fillna([np.nan])
但我收到错误
TypeError: "value" 参数必须是标量或字典,但你传递的是 "list"
TypeError: "value" parameter must be a scalar or dict, but you passed a "list"
对实现这一目标的简单方法有什么建议吗?
Any suggestions of a simple way to acheive this?
推荐答案
使用 apply
,因为 fillna
仅适用于标量:
Use apply
, because fillna
working with scalars only:
print (ser.apply(lambda x: [np.nan] if pd.isnull(x) else x))
0 0
1 1
2 [nan]
dtype: object
这篇关于使用 fillna 在 Pandas 中使用列表填充空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文