繁体   English   中英

通过将另一列与第二个DataFrame进行比较,替换一列中的值

[英]Replace values from one column by comparing another column to a second DataFrame

我正在尝试使用涉及搜索另一个DataFrame的特定条件替换df DataFrame的air_store_id列中的NaN值:

data = { 'air_store_id':     [ 'air_a1',   np.nan, 'air_a3',   np.nan,  'air_a5' ], 
         'hpg_store_id':     [ 'hpg_a1', 'hpg_a2',   np.nan, 'hpg_a4',    np.nan ],
                 'Test':     [ 'Alpha',    'Beta',  'Gamma',  'Delta', 'Epsilon' ]
       }

df = pd.DataFrame(data)
display(df)

在此输入图像描述

当在df.air_store_id找到NaN时,我想使用df.hpg_store_id的值(当有一个时)将其与另一个名为id_table_df的同一列进行比较,并检索其air_store_id

这是id_table_df样子:

ids_data = { 'air_store_id':     [ 'air_a1', 'air_a4', 'air_a3', 'air_a2' ], 
             'hpg_store_id':     [ 'hpg_a1', 'hpg_a4', 'hpg_a3', 'hpg_a2' ] }

id_table_df = pd.DataFrame(ids_data)
display(id_table_df)

在此输入图像描述

简单地说,对于每一个 df.air_store_id取代它在适当当量id_table_df.air_store_id通过比较df.hpg_store_idid_table_df.hpg_store_id

在这种情况下, id_table_df最终作为查找表工作 生成的DataFrame看起来像这样:

在此输入图像描述

试图将它们与以下指令合并 ,但会引发错误:

df.loc[df.air_store_id.isnull(), 'air_store_id'] = df.merge(id_table_df, on='hpg_store_id', how='left')['air_store_id']

错误信息:

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2441             try:
-> 2442                 return self._engine.get_loc(key)
   2443             except KeyError:
...
...
...
KeyError: 'air_store_id'

问题1:我怎样才能完成?

问题2:有没有办法同时为两列( air_store_idhpg_store_id )执行此操作? 如果可能的话,我不必为每列单独运行合并。

set_index上使用pd.Series.map后使用id_table_df

df.fillna(
    df.hpg_store_id.map(
        id_table_df.set_index('hpg_store_id').air_store_id
    ).to_frame('air_store_id')
)

      Test air_store_id hpg_store_id
0    Alpha       air_a1       hpg_a1
1     Beta       air_a2       hpg_a2
2    Gamma       air_a3          NaN
3    Delta       air_a4       hpg_a4
4  Epsilon       air_a5          NaN

同时

v = id_table_df.values
a2h = dict(v)
h2a = dict(v[:, ::-1])
df.fillna(
    pd.concat([
        df.hpg_store_id.map(h2a),
        df.air_store_id.map(a2h),
    ], axis=1, keys=['air_store_id', 'hpg_store_id'])
)

      Test air_store_id hpg_store_id
0    Alpha       air_a1       hpg_a1
1     Beta       air_a2       hpg_a2
2    Gamma       air_a3       hpg_a3
3    Delta       air_a4       hpg_a4
4  Epsilon       air_a5          NaN

创意解决方案
需要Python 3

v = id_table_df.values
a2h = dict(v)
h2a = dict(v[:, ::-1])
col = id_table_df.columns
swch = dict(zip(col, col[::-1]))
df.fillna(df.applymap({**a2h, **h2a}.get).rename(columns=swch))

      Test air_store_id hpg_store_id
0    Alpha       air_a1       hpg_a1
1     Beta       air_a2       hpg_a2
2    Gamma       air_a3       hpg_a3
3    Delta       air_a4       hpg_a4
4  Epsilon       air_a5         None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM