首页 > 解决方案 > 根据差异过滤数据帧有两个系列,一个通过字典映射

问题描述

我有我的字典

d = {'A':1, 'B':2, 'C':3}

和我的数据框

df =pd.DataFrame({
"col1": ["A", "B", "C"],
"col2": [1, 2, 3],
"col3": [2, 1, 4] })

我搜索将 df 中的每个值与字典中的对应值进行比较。如果匹配,则保留该值,否则丢弃该值。

我试试

m = df['col2'] >= d[df['col1']]
df.where(m, df, other = "")

但它得到了 m 的错误代码:TypeError: 'Series' objects are mutable, 因此它们不能被散列......

谢谢您的帮助。

标签: pythonpandasdictionarydataframeindexing

解决方案


使用 apply 创建一个新列进行比较

df[‘dict_col’] = df[‘col1’].apply(lambda k: d[k])

m = df[‘dict_col’] >= df[‘col2’]

df[‘col2’] = df[‘col2’].where(m, df, other = "")

推荐阅读