我正在尝试更改数据框中仅某些值的值:
test = pd.DataFrame({'col1': ['a', 'a', 'b', 'c'], 'col2': [1, 2, 3, 4]})
dict_curr = {'a':2}
test['col2'] = np.where(test.col1 == 'a', test.col1.map(lambda x: dict_curr[x]), test.col2)
但是,这似乎不起作用,因为即使我只查看col1中的值“ a”,该错误仍显示为
KeyError: 'b'
举例来说,它还会查看col1的值为“ b”的值。为什么是这样?以及我该如何解决?
答案 0 :(得分:1)
问题在于,当您调用np.where
时,将首先评估其所有参数,然后根据条件决定结果。因此,即使'b'
和'c'
也要查询字典,即使这些值以后会被丢弃。可能最简单的解决方法是:
import pandas as pd
import numpy as np
test = pd.DataFrame({'col1': ['a', 'a', 'b', 'c'], 'col2': [1, 2, 3, 4]})
dict_curr = {'a': 2}
test['col2'] = np.where(test.col1 == 'a', test.col1.map(lambda x: dict_curr.get(x, 0)), test.col2)
这将为不在字典中的键提供值0
,但由于以后将被丢弃,因此使用哪个值都没有关系。
获得相同结果的另一种简便方法是:
import pandas as pd
test = pd.DataFrame({'col1': ['a', 'a', 'b', 'c'], 'col2': [1, 2, 3, 4]})
dict_curr = {'a': 2}
test['col2'] = test.apply(lambda x: dict_curr.get(x.col1, x.col2), axis=1)
答案 1 :(得分:1)
该错误源自test.col1.map(lambda x: dict_curr[x])
部分。您可以在col1
的{{1}}中查找值,该值仅包含dict_curr
的条目,而没有'a'
的条目。
您也可以只索引数据框:
'b'