Reputation: 1
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?
Upvotes: 0
Views: 114
Reputation: 1979
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'>
Upvotes: 0
Reputation: 4761
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'}
Upvotes: 1