python - 从列中在熊猫中附加键值
问题描述
我有以下数据。我需要从中形成一本字典。y1_bin、y2_bin、.....y20_bin 共有 20 列。在这个玩具数据中,我只显示了三列。
Firm y1 y2 y3 prob_y1 prob_y2 prob_y3 y1_bin y2_bin y3_bin
0 A 1 2 7 0.006897 0.000421 0.002729 binA binA binB
1 B 2 3 45 0.013793 0.000632 0.017544 binA binA binE
2 C 3 4 40 0.020690 0.000842 0.015595 binA binA binE
3 D 4 7 3 0.027586 0.001474 0.001170 binA binB binA
4 E 5 9 4 0.034483 0.001895 0.001559 binB binB binA
5 F 6 400 12 0.041379 0.084211 0.004678 binB binH binC
6 G 7 50 32 0.048276 0.010526 0.012476 binB binF binE
7 H 8 70 0 0.055172 0.014737 0.000000 binB binF binA
8 I 9 95 76 0.062069 0.020000 0.029630 binB binF binF
9 J 10 98 1 0.068966 0.020632 0.000390 binC binF binA
10 K 20 2 45 0.137931 0.000421 0.017544 binD binA binE
11 L 30 10 2000 0.206897 0.002105 0.779727 binE binC binH
12 M 40 4000 300 0.275862 0.842105 0.116959 binE binH binH
我编写了以下语法来附加键和值:
from collections import defaultdict
mydict = defaultdict(list)
for k, v, m,j in zip(df33.Firm.values, df33.y2_bin.values, df33.y1_bin.values, df33.y3_bin.values):
mydict[k].append(v)
mydict[k].append(m)
mydict[k].append(j)
print(mydict)
这是预期的结果(我可以从上面的 for 循环中得到——而且我知道这不是编写代码的最有效方法。)。有没有更好的方法来提高效率,这样我就不必在 for 循环中不断添加df33.***.values
和 。mydict[k].append(****)
defaultdict(<type 'list'>, {'A': ['binA', 'binA', 'binB'], 'C': ['binA', 'binA', 'binE'], 'B': ['binA', 'binA', 'binE'], 'E': ['binB', 'binB', 'binA'], 'D': ['binB', 'binA', 'binA'], 'G': ['binF', 'binB', 'binE'], 'F': ['binH', 'binB', 'binC'], 'I': ['binF', 'binB', 'binF'], 'H': ['binF', 'binB', 'binA'], 'K': ['binA', 'binD', 'binE'], 'J': ['binF', 'binC', 'binA'], 'M': ['binH', 'binE', 'binH'], 'L': ['binC', 'binE', 'binH']})
解决方案
如何使用DataFrame.to_dict
具有列表理解的方法如下:
import pandas as pd
df = pd.DataFrame([
{'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'B', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
{'Firm': 'B', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
])
# set column 'Firm' as the index (needed for df.to_dict() to work)
df.set_index('Firm', inplace=True)
my_dict = {k: list(v.values()) for k, v in df.to_dict('index').items()}
# output:
{'A': ['binA', 'binA', 'binB'], 'B': ['binA', 'binA', 'binB']}
查看to_dict以获取有关其输出的更多信息
推荐阅读
- node.js - 自定义错误处理程序在 Express 中不起作用
- python - 更新函数并从 scipy 获取迭代结果
- vb.net - 自定义类 vb.net 中未定义类型“记录”
- python - 具有对数比例颜色图的 Geopandas
- javascript - 从回调函数中提取处理响应的通用代码
- javascript - 正则表达式提取第二和第三个字符串
- c++ - 如何使用多核和多线程来获得最大的 cpu 和 I/O 容量来加速 C++ 中的程序?
- python - 匹配 2 个文本文件中的文本并从第一个文件获取信息并附加到另一个文件
- c - 如何在二进制模式下使用 C 中的嵌套结构
- algorithm - 在螺旋填充矩阵的特定索引处查找数字