我有一个数据框和nparray,如下所示
import pandas as pd
import numpy as np
dic = {'A': {0: 0.9, 1: "NaN", 2: 1.8, 3: "NaN"},
'C': {0: 0.1, 1: 2.8, 2: -0.1, 3: 0.5},
'B': {0: 0.7, 1: -0.6, 2: -0.1, 3: -0.1},}
df=pd.DataFrame(dic)
print(df)
A C B
0 0.9 0.1 0.7
1 NaN 2.8 -0.6
2 1.8 -0.1 -0.1
3 NaN 0.5 -0.1
a = np.array([1.,2.])
a
array([1., 2.])
我如何用nparray中的值填充A列中缺少的(NaN)值?我想根据数组的顺序依次填充列,因此第一个数组元素变为1A,第二个数组元素变为3A。
答案 0 :(得分:1)
使用numpy.tile
通过重复a
的元素来创建数组
df['A'].replace('NaN', np.nan, inplace = True)
len_tile = math.ceil(df['A'].isnull().sum()/len(a))
non_null_a = np.tile(a, len_tile)
然后使用“ loc”使用数组填充NaN,
df.loc[df['A'].isnull(), 'A'] = non_null_a
A C B
0 0.9 0.1 0.7
1 1.0 2.8 -0.6
2 1.8 -0.1 -0.1
3 2.0 0.5 -0.1
注意:对于您提供的虚拟df,只需使用数组a
来替换缺少的值即可。我使用的代码考虑了NaN比数组长度更多的情况。