【问题标题】:How to create a new pandas dataframe with multiple, custom index names?如何创建具有多个自定义索引名称的新熊猫数据框?
【发布时间】:2018-02-19 13:17:41
【问题描述】:

基于this answer,我已经能够使用我自己的数据和指定的数据类型创建一个新的熊猫数据框,如下所示:

df = pd.DataFrame({'A':pd.Series([1], dtype='str'),
                   'B':pd.Series([4], dtype='int'),
                   'C':pd.Series([7], dtype='float')})

print(df)
   A  B    C
0  1  4  7.0

但是,我需要的是能够在创建数据框时额外指定索引名称。我想这应该使用pd.DataFrame() 和/或pd.Series() 的索引参数来完成,但我不确定以什么方式。

预期结果是,如果我之后打印df,我会得到:

             A  B    C
idx1  idx2
0     test   1  4  7.0

其中"idx1""idx2" 是索引名称,0"test" 是此(单行)数据框中的第一行对于两个索引的值。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    需要为每个Series 定义MultiIndex,例如MultiIndex.from_arrays:

    mux = pd.MultiIndex.from_arrays([[0], ['test']], names=['idx1','idx2'])
    df = pd.DataFrame({'A':pd.Series([1], dtype='str', index=mux),
                       'B':pd.Series([4], dtype='int', index=mux),
                       'C':pd.Series([7], dtype='float', index=mux)})
    
    print(df)
    
               A  B    C
    idx1 idx2           
    0    test  1  4  7.0
    

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 2017-05-31
      • 2016-02-05
      • 2016-01-13
      • 2015-03-22
      • 2014-02-10
      • 2015-02-22
      • 2018-11-09
      • 2016-06-24
      相关资源
      最近更新 更多