【发布时间】:2021-06-24 18:15:47
【问题描述】:
我有一个如下图所示的数据框
df = pd.DataFrame({'source_code':['11','11','12','13','14',np.nan],
'source_description':['test1', 'test1','test2','test3',np.nan,'test5'],
'key_id':[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
我还有一个如下所示的 hash_file 数据框
hash_file = pd.DataFrame({'source_id':['11','12','13','14','15'],
'source_code':['test1','test2','test3','test4','test5'],
'hash_id':[911,512,713,814,616]})
id_file = hash_file.set_index(['source_id','source_code'])['hash_id']
id_file 中不会有重复项(source_id,source_code)将始终是唯一的
现在,我想根据来自hash_file 的source_code、source_description 与source_id 和source_code 列的匹配条目来填写df 中的key_id 列。
所以,我尝试了以下
df['key_id'] = df['source_code','source_description'].map(id_file)
报错了
KeyError: ('source_code', 'source_description')
所以,我在下面尝试了另一种方法
df['key_id'] = df[['source_code','source_description']].map(id_file)
又抛出一个错误
AttributeError: 'DataFrame' 对象没有属性 'map'
所以,我希望我的输出如下所示。请注意,两者之间可能有NA,它必须不区分大小写。这意味着id_file 中的索引与df 中的列的比较必须不区分大小写。
我只想使用map 方法。也欢迎任何其他优雅的方法
source_code source_description key_id
11 test1 911
11 test1 911
12 test2 512
13 test3 713
14 NaN 814
NaN test5 616
【问题讨论】:
-
能否详细说明
there might be NA in between? -
意思是
source_id或source_code列(任一列)可以是NA.. -
在这种情况下,您希望如何将值映射到
df? -
我更新了输出。代码应比较两列以获取 key_ids。如果其中一列是
NA,那么它应该查看另一列并尝试根据它找到匹配项 -
我更喜欢
map而不是合并,因为对于single列,它可以正常工作并且只需一行代码.. 对非程序员来说也很容易理解..我也想做同样的事情map用于多个键列.. 因此映射合并
标签: python pandas dataframe dictionary series