首页 文章

如何使用多个自定义索引名称创建新的pandas数据框?

提问于
浏览
1

基于this answer,我已经能够使用我自己的数据和指定的dtypes创建一个新的pandas数据帧,如下所示:

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() 的索引参数来完成,但我不确定以什么方式 .

intended result 是,如果我之后打印 df ,我得到:

A  B    C
idx1  idx2
0     test   1  4  7.0

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

1 回答

  • 1

    需要为每个 Series 定义 MultiIndex ,例如by 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
    

相关问题