【问题标题】:Setting the index for a pandas dataframe Python为 pandas 数据框 Python 设置索引
【发布时间】:2021-12-31 23:41:22
【问题描述】:

下面的代码从下面的字典中创建了一堆数据表。我正在尝试将Values 添加为所有数据表的索引参数,但它们所有的表值都变成nan。我将如何更改它,以便将索引 0 to 2 替换为 First, Second, Third

字典:

Outcomes = {
    'Values':{
        'First': {
            'option 1': np.array([12,345,5412]),
            'option 2': np.array([2315,32,1]),
            'option 3': {'row 1': np.array([232,3,1]),
                         'row 2': np.array([3,4,5]),
                         'row 3': np.array([15,6,12])}
        }
        
    }
}

代码:

import pandas as pd 
import numpy as np 

Values = ['First', 'Second', 'Third']

def get_nested_df(dic, concat_key="", df_dic=dict()):
   rows = {k:v for k,v in dic.items() if not isinstance(v, dict)}
   if rows:
      df_dic.update({concat_key: pd.DataFrame.from_dict(rows)})
   for k,v in dic.items():
      if isinstance(v, dict):
         get_nested_df(v, f"{concat_key} {k}", df_dic)
   return df_dic

df_dic = get_nested_df(Outcomes)

for k,v in df_dic.items():
    #print(f"{k}\n{v}\n")
    display(pd.DataFrame(v, index=Values).style.set_caption(k).set_table_styles([{
        'selector': 'caption',
        'props': [
            ('color', 'red'),
            ('font-size', '16px'),
            ('text-align', 'center')
        ]
    }]))

输出:

【问题讨论】:

  • v 已经是一个DataFrame,所以你可以用v.index = Values 设置它的索引。要将表格呈现为 HTML 吗?

标签: python pandas database function dictionary


【解决方案1】:

考虑改用下一个代码:

for k,v in df_dic.items():
    #print(f"{k}\n{v}\n")
    v.index = pd.Index(Values)
    v.style.set_caption(k).set_table_styles([{
        'selector': 'caption',
        'props': [
            ('color', 'red'),
            ('font-size', '16px'),
            ('text-align', 'center')
        ]
    }])
    display(v)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2020-10-22
    • 2020-06-02
    • 1970-01-01
    • 2014-10-05
    • 2014-07-10
    相关资源
    最近更新 更多