[英]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.