首页 > 解决方案 > 如何在保留 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 的同时将某些列组合移动到字典中?

标签: pythonpandasdataframe

解决方案


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

推荐阅读