简体   繁体   中英

How to convert a Pandas dataframe to dictionary while retaining dtype?

I have a dataframe (simplified):

      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

which I would like to select columns from to make a dictionary:

lows = { 'amount' : 2.5,
                'grind_size' : 8,
                'brew_time': 3.5,
                'grind_type': 'burr',
                'beans': 'light' }

However when I run:

lows = dict(zip(df.Factors, df.low))

I get:

 {'amount': '2.5', 
'grind_size': '8', 
'brew_time': '3.5', 
'grind_type': 'burr', 
'beans': 'light'}

How can move certain combinations of columns to a dictionary while retaining the integer 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'}

You can try (perhaps not the cleanest, but it seems to do what you want):

>>> 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'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM