有没有一种方便的方法用数组或列的(第一个)值填充na值?在
设想以下数据帧:
dfcolors = pd.DataFrame({'Colors': ['Blue', 'Red', np.nan, 'Green', np.nan, np.nan, 'Brown']})
Colors
0 Blue
1 Red
2 NaN
3 Green
4 NaN
5 NaN
6 Brown
我想用另一个数据帧或数组中的值填充NaN值,因此:
^{pr2}$当有更多的NaN填充值时,一些NaN应该保留。当填充值更多时,并不是所有的填充值都将被使用。所以我们得数数:
n_missing = len(dfcolors) - dfcolors.count().values[0]
n_fill = min(n_missing, len(dfalt))
数字n_fill
是可以填充的值的数量。在
选择可以/应该填充的NaN值可以通过以下方法完成:
dfcolors.Colors[pd.isnull(dfcolors.Colors)][:n_fill]
2 NaN
4 NaN
Name: Colors, dtype: object
选择填充值
dfalt.Alt[:n_fill]
0 Cyan
1 Pink
Name: Alt, dtype: object
他们让我陷入了这样的困境:
dfcolors.Colors[pd.isnull(dfcolors.Colors)][:n_fill] = dfalt.Alt[:n_fill]
这不管用。。。有什么建议就好了。在
这是我想要的输出:
Colors
0 Blue
1 Red
2 Cyan
3 Green
4 Pink
5 NaN
6 Brown
从上到下填充NaN值,如果填充值多于NaN值,则填充值也将从上到下进行选择
你可以用发电机。你可以这样写:
这是相当糟糕的,但是迭代null的索引是有效的:
相关问题 更多 >
编程相关推荐