Pandas fillna与列表/数组

2024-10-01 19:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方便的方法用数组或列的(第一个)值填充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值,则填充值也将从上到下进行选择


Tags: 方法npgreenbluered数组nanalt
2条回答

你可以用发电机。你可以这样写:

import pandas as pd
from pandas import np

dfcolors = pd.DataFrame({'Colors': ['Blue', 'Red', np.nan, 'Green', np.nan, np.nan, 'Brown']})
dfalt = pd.DataFrame({'Alt': ['Cyan', 'Pink']})

gen_alt = (alt for alt in dfalt.Alt)

for i, color in enumerate(dfcolors.Colors):
    if not pd.isnull(color): continue
    try:
        dfcolors.Colors[i] = gen_alt.next()
    except StopIteration:
        break
print(dfcolors)
#     Colors
# 0   Blue
# 1    Red
# 2   Cyan
# 3  Green
# 4   Pink
# 5    NaN
# 6  Brown

这是相当糟糕的,但是迭代null的索引是有效的:

In [11]: nulls = dfcolors[pd.isnull(dfcolors['Colors'])]

In [12]: for i, ni in enumerate(nulls.index[:len(dfalt)]):
             dfcolors['Colors'].loc[ni] = dfalt['Alt'].iloc[i]

In [13]: dfcolors
Out[13]:
  Colors
0   Blue
1    Red
2   Cyan
3  Green
4   Pink
5    NaN
6  Brown

相关问题 更多 >

    热门问题