【问题标题】:convert dataframe type object to dictionary将数据框类型对象转换为字典
【发布时间】:2017-06-13 05:52:31
【问题描述】:

我有数据框 best_scores 包含

     subsample colsample_bytree learning_rate max_depth min_child_weight  \
3321       0.8              0.8           0.3         2                3   

            objective  scale_pos_weight  silent  
3321  binary:logistic          1.846154       1  

我想把它转换成字典params,比如:

params
{'colsample_bytree': 0.8,
  'learning_rate': 0.3,
  'max_depth': 2,
  'min_child_weight': 3,
  'objective': 'binary:logistic',
  'scale_pos_weight': 1.8461538461538463,
  'silent': 1,
  'subsample': 0.8}

但是如果我跑了

best_scores.to_dict(orient='records')

我明白了:

[{'colsample_bytree': 0.8,
  'learning_rate': 0.3,
  'max_depth': 2,
  'min_child_weight': 3,
  'objective': 'binary:logistic',
  'scale_pos_weight': 1.8461538461538463,
  'silent': 1L,
  'subsample': 0.8}]

你能帮忙吗?

【问题讨论】:

  • 你不行吗best_scores.to_dict(orient='records')[0]
  • @Jean-FrançoisFabre 谢谢!任何线索为什么沉默是 L 而不是 int?
  • 可能是因为它是用 long int 初始化的。您必须使用 python 2。您可以转换回 int。别担心,它工作正常(只是占用更多内存而已)

标签: python pandas dictionary dataframe


【解决方案1】:

您将获得一个字典列表,因为您将 DataFrame 转换为 dict,它可能有多个行。每行将是列表中的一个条目。

除了提到的简单地选择第一个条目的解决方案之外,实现您想要的理想方法是使用Series 而不是DataFrame。这样,只返回一个dict

In [2]: s = pd.Series([1, 2 ,3], index=['a', 'b', 'c'])

In [3]: s.to_dict()
Out[3]: {'a': 1, 'b': 2, 'c': 3}

In [4]: d = pd.DataFrame(s).T

In [5]: d
Out[5]: 
   a  b  c
0  1  2  3

In [6]: d.iloc[0]
Out[6]: 
a    1
b    2
c    3
Name: 0, dtype: int64

In [7]: d.iloc[0].to_dict()
Out[7]: {'a': 1, 'b': 2, 'c': 3}

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2022-07-05
    • 2021-08-29
    • 2019-08-02
    • 1970-01-01
    • 2021-06-19
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多