python - 根据差异过滤数据帧有两个系列,一个通过字典映射
问题描述
我有我的字典
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, 因此它们不能被散列......
谢谢您的帮助。
解决方案
使用 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 = "")
推荐阅读
- reactjs - 每个 React Native 的 API Fetch - 与浏览器相比不同的终端日志
- security - 能否在 Outlook 365 中禁用 MAPI?
- redirect - 调用重定向的 websphere 应用程序服务器会导致创建新会话
- python - 如何在python3中以二进制模式将多个数据类型的值保存在.txt文件中?
- javascript - Shadow Dom 支持制表符表
- google-cloud-platform - 将 GCP Cloud IAM 自定义角色的访问权限仅限于存储桶
- css - 在 Angular (CSS) 中使用网格
- facebook-graph-api - 有没有办法使用 facebook API 获取用户的工作历史记录?
- django - 如何在 django 中保存生成 otp 代码
- git - 在本地删除特定的提交