python将第一列替换_python-通过将另一列与第二个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的 dataframe 的同一列进行比较,并检索其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中的每个NaN,通过将df.hpg_store_id与id_table_df.hpg_store_id进行比较,将其替换为id_table_df.air_store_id中的相应等价物.
在这种情况下,id_table_df最终用作查找表.产生的DataFrame如下所示:
我使用以下指令进行了tried to merge them的操作,但引发了错误:
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_id和hpg_store_id)执行此操作?如果可能的话,我不必为每个列分别运行合并.
总结
以上是生活随笔为你收集整理的python将第一列替换_python-通过将另一列与第二个DataFrame进行比较来替换一列中的值...的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 白钢条用什么可以切割_错怪李佳琦了!原来
- 下一篇: python设计模式六大原则_php设计