如何填充NAN“忽略”索引?

Cle*_*leb 4 python dataframe pandas fillna

我有两个这样的数据框:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(
    {
        'A': list('abdcde'),
        'B': ['s', np.nan, 'h', 'j', np.nan, 'g']
    }
)

df2 = pd.DataFrame(
    {
        'mapcol': list('abpppozl')
    }
)

   A    B
0  a    s
1  b  NaN
2  d    h
3  c    j
4  d  NaN
5  e    g

  mapcol
0      a
1      b
2      p
3      p
4      p
5      o
6      z
7      l
Run Code Online (Sandbox Code Playgroud)

我现在想,以填补Bdf1使用的值df2['mapcol'],但是没有使用的实际指标,但-在这种情况下-只是前两个项目df2['mapcol']。因此,而不是bp对应于指数14分别,我想用数值ab

一种方法是构造一个具有正确索引和值的字典:

df1['B_filled_incorrect'] = df1['B'].fillna(df2['mapcol'])

ind = df1[df1['B'].isna()].index

# reset_index is required as we might have a non-numerical index
val = df2.reset_index().loc[:len(ind-1), 'mapcol'].values

map_dict = dict(zip(ind, val))

df1['B_filled_correct'] = df1['B'].fillna(map_dict)

   A    B B_filled_incorrect B_filled_correct
0  a    s                  s                s
1  b  NaN                  b                a
2  d    h                  h                h
3  c    j                  j                j
4  d  NaN                  p                b
5  e    g                  g                g
Run Code Online (Sandbox Code Playgroud)

这给出了所需的输出。

有没有更直接的方法可以避免创建所有这些中间变量?

WeN*_*Ben 5

位置填充您可以通过分配值loc并将填充值转换为list

df1.loc[df1.B.isna(),'B']=df2.mapcol.iloc[:df1.B.isna().sum()].tolist()
df1
Out[232]: 
   A  B
0  a  s
1  b  a
2  d  h
3  c  j
4  d  b
5  e  g
Run Code Online (Sandbox Code Playgroud)