[英]How to convert a Pandas dataframe to dictionary while retaining dtype?
我有一个 dataframe(简体):
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
我想用 select 列来制作字典:
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'}
如何在保留 integer dtype 的同时将某些列组合移动到字典中?
强制铸造怎么样? 看起来您的 dataframe 中的数字实际上是str
实例。
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'}
您可以尝试(也许不是最干净的,但它似乎可以满足您的要求):
>>> df = pd.DataFrame({'Factors' : ['amount', 'grind_size', 'brew_time', 'grind_type', 'beans'], 'low' : [2.5, 8, 3.5, 'burr', 'light'], 'high' : [4, 10, 4.5, 'blade', 'dark']})
>>> df
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
>>>
>>> df[['Factors', 'low']].set_index('Factors').T.to_dict('records')[0]
{'amount': 2.5, 'grind_size': 8, 'brew_time': 3.5, 'grind_type': 'burr', 'beans': 'light'}
>>>
>>> # check the types
>>> for k, v in df[['Factors', 'low']].set_index('Factors').T.to_dict('records')[0].items():
... print(f'key: {k}, val: {v}, type_val: {type(v)}')
...
key: amount, val: 2.5, type_val: <class 'float'>
key: grind_size, val: 8, type_val: <class 'int'>
key: brew_time, val: 3.5, type_val: <class 'float'>
key: grind_type, val: burr, type_val: <class 'str'>
key: beans, val: light, type_val: <class 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.