代码之家  ›  专栏  ›  技术社区  ›  errEstiak

Python Pandas数据帧行名称更改

  •  1
  • errEstiak  · 技术社区  · 1 年前

    如何将第一个索引0替换为 “颜色” 1与 “大小”?

    import pandas as pd
    clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]}
    
    # pd.DataFrame.from_dict(clothes)
    df = pd.DataFrame.from_dict(clothes)
    df
    

    我试着这样做,但没有任何改变。输出将索引名称显示为错误

    df = pd.DataFrame.from_dict(clothes, index = ['color', 'size'])
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   mozway    1 年前

    不要使用 from_dict ,但是 DataFrame 构造函数直接:

    df = pd.DataFrame(clothes, index=['color', 'size'])
    

    如果DataFrame已经存在, set_axis :

    df = pd.DataFrame(clothes)
    
    df = df.set_axis(['color', 'size'])
    

    输出:

          shirt sweater jacket
    color   red  yellow  black
    size      M       L      L