将字典字典导入DataFrame后,按索引排序数据

时间:2017-03-28 17:04:15

标签: python pandas dictionary dataframe

我正在尝试按索引重新排序DataFrame。此DataFrame是从字典字典创建的。我正在尝试使用DataFrame.sort_values。虽然,当我尝试打印DataFrame时,排序完全没有区别。

以下代码举例说明了我要实现的目标:

import pandas as pd

# Metrics dictionary keys
GOLD_CNT_KEY = 'Gold_Cnt'
PRED_CNT_KEY = 'Pred_Cnt'
NER_INTERSEC_CNT_KEY = 'NER_Intersec_Cnt'
NER_PREC_KEY = 'NER_Precision'
NER_REC_KEY = 'NER_Recall'
NER_F1_KEY = 'NER_F1'
NERC_INTERSEC_CNT_KEY = 'NERC_Intersec_Cnt'
NERC_PREC_KEY = 'NERC_Precision'
NERC_REC_KEY = 'NERC_Recall'
NERC_F1_KEY = 'NERC_F1'

tag_classes = ['X', 'Y', 'Z', 'V']

def get_empty_stats_dict():
    """Dictionary for the counts and metrics"""
    return {GOLD_CNT_KEY: 0,
            PRED_CNT_KEY: 0,
            NER_INTERSEC_CNT_KEY: 0,
            NER_PREC_KEY: 0,
            NER_REC_KEY: 0,
            NER_F1_KEY: 0,
            NERC_INTERSEC_CNT_KEY: 0,
            NERC_PREC_KEY: 0,
            NERC_REC_KEY: 0,
            NERC_F1_KEY: 0}

stats = {}
for tag_class in tag_classes:
    stats.update({tag_class: get_empty_stats_dict()})
# I want to order by these indexes
index_order = [GOLD_CNT_KEY, PRED_CNT_KEY, NER_INTERSEC_CNT_KEY, NERC_INTERSEC_CNT_KEY,
               NER_PREC_KEY, NERC_PREC_KEY, NER_REC_KEY, NERC_REC_KEY, NER_F1_KEY, NERC_F1_KEY]

_stats = pd.DataFrame(stats)

# These two prints yield exactly the same output. Why doesn't sort_values make any difference?
print(_stats)
print(_stats.sort_values(index_order, axis=1))

1 个答案:

答案 0 :(得分:1)

尝试:_stats = _stats.reindex(index_order)