python - 如何在保留 dtype 的同时将 Pandas 数据框转换为字典?
问题描述
我有一个数据框(简化):
Factors low high
0 amount 2.5 4
1 grind_size 8 10
2 brew_time 3.5 4.5
3 grind_type burr blade
4 beans light dark
我想从中选择列来制作字典:
lows = { 'amount' : 2.5,
'grind_size' : 8,
'brew_time': 3.5,
'grind_type': 'burr',
'beans': 'light' }
但是,当我运行时:
lows = dict(zip(df.Factors, df.low))
我得到:
{'amount': '2.5',
'grind_size': '8',
'brew_time': '3.5',
'grind_type': 'burr',
'beans': 'light'}
如何在保留整数 dtype 的同时将某些列组合移动到字典中?
解决方案
What about forcing a casting? It looks like the numbers in your dataframe are actually str
instances.
def to_float(val):
try:
val = float(val)
except ValueError:
pass
return val
lows = dict(zip(df.Factors, map(to_float, df.low)))
print(lows)
#{'amount': 2.5, 'grind_size': 8.0, 'brew_type': 3.5, 'grind_type': 'burr', 'beans': 'light'}
推荐阅读
- elasticsearch - Kibana 无法加载仪表板的问题(退出:资源 'metricbeat-7.5.0' 存在,但它不是别名)
- python - 如何修改我的 python 套接字服务器代码以适应两个客户端?
- javascript - 如何在 javascript 中将二维数组作为参数传递?
- python - 如何为图像帧中的每个垂直分辨率分辨率单元分配角度?
- php - Yii2 不为空条件的左连接查询
- python - Spyder中的Python For循环调试
- git - git rebase 在上游变得无效
- python - 遍历字典以获取值
- prometheus - 如何将元素(标签)添加到 Prometheus 查询以在 Grafana 中使用
- google-bigquery - FROM 子句中的多个表如何在 BigQuery 中工作