如何从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
相关产品推荐
相关产品推荐

