python - 将数据框与字典值列表进行比较

标签 python pandas dictionary

我有一个数据框:

d = {'col1':['2q','48', '48-49']}
test = pd.DataFrame(d)


col1

0 2q
1 48 
2 48-49 

还有一个映射字典:

mupcs_to_pc_mapping = {'24': ['48-49', '48', '49'], #M2
                   '23': ['50-51', '50', '51'], #M3
                   '22': ['52-53', '52', '53'], #M4
                   '21': ['54-55', '54', '55'], #M5
                  }

我想测试测试数据帧的每个值,看看它是否存在于 mupcs_to_pc_mapping 字典值中。

所以最终的结果是这样的:

0 False
1 True
2 True

我尝试了以下变体:

test['col1'].isin(mupcs_to_pc_mapping.values())

test['col1'].any(value for value in mupcs_to_pc_mapping.values())

但两者都会导致错误。

有人知道我的代码有什么问题吗?

最佳答案

你也可以这样做:

test.isin(pd.DataFrame(mupcs_to_pc_mapping).stack().values)

   col1
0  False
1  True
2  True

关于python - 将数据框与字典值列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366585/

相关文章:

python - 将自定义梯度定义为 Tensorflow 中的类方法

python - 我如何在一个单元格中使用多个值进行一次热编码?

python - 使用ctypes按值调用python进行ref调用

python - 使用 pymongo 创建 map

python - 在 Python pandas 中自定义 rolling_apply 函数

python - Pandas :对一系列 bool 值进行和/或操作

ios - '(@lvalue Int) -> $T 7' is not identical to ' 字典 <Int,Int>'

c# - 在 Repeater 中渲染超链接控件

python - 使用 Pandas 用连续值和以上行填充行

python - 压缩以下代码,最好使用字典理解