【发布时间】:2022-08-05 22:33:36
【问题描述】:
如果 pandas DataFrame 列中的值在字典的值中,如何返回字典键?
那么对于下面的df,您将如何根据col1 是否在字典的值中添加一个返回字典键的col3 列,即odd 或even?
df = pd.DataFrame({\"col1\": [1,2,3,4,5], \"col2\": [6,7,8,9,10]})
d = {\"odd\": [1,3,5,7,9], \"even\": [2,4,6,8,10]}
df[\"col3\"] = np.where(df[\"col1\"].isin(d.values), d.key, \"\") # ???
我知道您可以使用% 或其他东西来确定一个值是奇数还是偶数,以上只是一个示例,其他字典可能是我们需要读取的某种类型的配置文件或json。
希望能够产生这样的东西:
col1 col2 col3
0 1 6 odd
1 2 7 even
2 3 8 odd
3 4 9 even
4 5 10 odd
-
将您的字典重新映射到
number: result然后只是df[\'col\'].map(dictionary)