You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Pandas DataFrame生成两个指定规则的字典?

解决Pandas按条件生成字典的问题

原始DataFrame

import pandas as pd
df = pd.DataFrame({'A':['a_o','a','b_o','b','c'],'B':[1,0,1,1,0],'C':[99,24,67,89,91]})

需求

生成两个目标字典:

  • dict1 = {'a_o':99,'b_o':67}:A列以_o结尾的条目作为键,对应C列的值为值
  • dict2 = {'a':0,'b':1,'c':0}:A列中其余条目作为键,对应B列的值为值

解决方案

核心是用str.endswith('_o')筛选符合条件的行,再转换为字典:

生成dict1

# 筛选A列以"_o"结尾的行,提取A和C列生成字典
filtered_o_rows = df[df['A'].str.endswith('_o')]
dict1 = dict(zip(filtered_o_rows['A'], filtered_o_rows['C']))

或者更简洁的写法:

dict1 = df[df['A'].str.endswith('_o')].set_index('A')['C'].to_dict()

生成dict2

用~取反筛选出A列不以_o结尾的行:

# 筛选A列不以"_o"结尾的行,提取A和B列生成字典
filtered_rest_rows = df[~df['A'].str.endswith('_o')]
dict2 = dict(zip(filtered_rest_rows['A'], filtered_rest_rows['B']))

简洁写法:

dict2 = df[~df['A'].str.endswith('_o')].set_index('A')['B'].to_dict()

验证结果

运行上述代码后,dict1和dict2会完全符合预期要求。


内容的提问来源于stack exchange,提问作者User1917931829

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:27:11