Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环几个值以填充数据帧中的NAN_Python_Pandas_Dataframe_Series - Fatal编程技术网

Python 循环几个值以填充数据帧中的NAN

Python 循环几个值以填充数据帧中的NAN,python,pandas,dataframe,series,Python,Pandas,Dataframe,Series,我知道我不能像forfillna中所述,用列表填写NAN。那么,使用值列表填充NAN的首选方法是什么?期望的行为是浏览列表,一次填写一个NAN;如果NAN多于列表中的NAN,则重新开始。例如: np.random.seed(0) s = pd.Series(np.random.randint(0,100, 50)) s.loc[s > 25] = np.nan s.fillna([10, 20, 30]) # Produces TypeError 期望输出: 0 10 1 20

我知道我不能像for
fillna
中所述,用列表填写NAN。那么,使用值列表填充NAN的首选方法是什么?期望的行为是浏览列表,一次填写一个NAN;如果NAN多于列表中的NAN,则重新开始。例如:

np.random.seed(0)
s = pd.Series(np.random.randint(0,100, 50))
s.loc[s > 25] = np.nan
s.fillna([10, 20, 30]) # Produces TypeError 
期望输出:

0   10
1   20
2   30
3   10
4   20
5   9.0
6   30
7   21.0
8   10
等等

这不是因为很难矢量化而内置的吗?值得一提的是,这只是理论上的,我没有实际数据

使用

s.loc[s.isna()]=[10,20,30]*(s.isna().sum()//3)+[10,20,30][:s.isna().sum()%3]
s
Out[271]: 
0     10.0
1     20.0
2     30.0
3     10.0
4     20.0
5      9.0
6     30.0
...

无需先将值转换为
NaN
。那么让我们假设这个起点:

np.random.seed(0)
s = pd.Series(np.random.randint(0,100, 50))
然后,您可以使用:

或者,与:

结果:

print(s.head(10))
# 0    10
# 1    20
# 2    30
# 3    10
# 4    20
# 5     9
# 6    30
# 7    21
# 8    10
# 9    20
# dtype: int32

第二个很好,第一个对我不起作用-离开了这个系列unchanged@JoshFriedlander,奇怪,这两种方法都适用于我输入的数据。好的,我意识到我的错误-在分配NAN之前,你的方法有效。所以它应该是
mask=np.isnan(s)
,除此之外,谢谢!我喜欢它,它比其他选项更地道。@Josh Friedlander,是的,这里没有必要先转换为
NaN
,这只是一个额外的操作。
s = s.mask(s > 25, np.resize([10, 20, 30], len(s.index)))
print(s.head(10))
# 0    10
# 1    20
# 2    30
# 3    10
# 4    20
# 5     9
# 6    30
# 7    21
# 8    10
# 9    20
# dtype: int32