【问题标题】:How to have multi index on both rows and columns of a dataframe without using tuples?如何在不使用元组的情况下对数据框的行和列进行多索引?
【发布时间】:2018-03-30 15:50:27
【问题描述】:

有没有一种方法可以在不使用元组的情况下创建在行和列上都具有多索引的数据框?我的标签太长,无法手动输入元组(每个国家/地区 96 个国家和 26 个部门)。 Example of what I want

我试过了:

df_data.columns=label_df 

df_data_w = pd.concat([label_df, data],axis=1,ignore_index=False) 

这将标签 df 添加到前两列,但没有索引它。相反,我在dataframe

这里有一些代码可以使用:

import numpy as np
import pandas as pd

a = np.random.randint(low=0, high=10,size=9)
b = np.random.randint(low=0, high=10,size=9)
c = np.random.randint(low=0, high=10,size=9)
d = np.random.randint(low=0, high=10,size=9)
e = np.random.randint(low=0, high=10,size=9)
f = np.random.randint(low=0, high=10,size=9)
g = np.random.randint(low=0, high=10,size=9)
h = np.random.randint(low=0, high=10,size=9)
i = np.random.randint(low=0, high=10,size=9)

df = pd.DataFrame(data=[a,b,c,d,e,f,g,h,i])

Continent = ['Africa','Africa','Africa','North America', 'North America', 'North America', 'Europe','Europe','Europe']

Sectors = ['Agriculture','Industry','Domestic','Agriculture','Industry','Domestic','Agriculture','Industry','Domestic']

label_df = pd.DataFrame(data=[Continent, Sectors])

df.columns=label_df  

df_w_labels = pd.concat([label_df, data],axis=1,ignore_index=False)` 

这将标签作为我的 df 中的标题,但我也需要它们作为列,所以我尝试了 concat,它将标签 df 添加到前两列,但没有索引它。

【问题讨论】:

  • 欢迎来到 SO。请提供 minimal reproducible example。这意味着您的问题中没有链接,没有图像,只有文字。祝你好运!
  • 感谢@jpp - 我的第一个 SO 帖子。已编辑希望对您有所帮助。
  • 澄清一下,虽然您有很多标签,但您只有两个级别,对吗? “国家”和“部门”?
  • 嗨@Ajean 是的,只有两个级别:国家和部门。

标签: python pandas labels multi-index


【解决方案1】:

您可以将ziplistpd.MultiIndex 一起使用:

a = np.random.randint(low=0, high=10,size=9)
b = np.random.randint(low=0, high=10,size=9)
c = np.random.randint(low=0, high=10,size=9)
d = np.random.randint(low=0, high=10,size=9)
e = np.random.randint(low=0, high=10,size=9)
f = np.random.randint(low=0, high=10,size=9)
g = np.random.randint(low=0, high=10,size=9)
h = np.random.randint(low=0, high=10,size=9)
i = np.random.randint(low=0, high=10,size=9)

df = pd.DataFrame(data=[a,b,c,d,e,f,g,h,i])

Continent = ['Africa','Africa','Africa','North America', 'North America', 'North America', 'Europe','Europe','Europe']
Sectors = ['Agriculture','Industry','Domestic','Agriculture','Industry','Domestic','Agriculture','Industry','Domestic']

indx = pd.MultiIndex.from_tuples(list(zip(Continent,Sectors)))

df.index = indx
df.columns = indx

print(df)

【讨论】:

  • 感谢 Scott Boston,这很有帮助。我认为我的主要问题是将 .csv 文件中的列转换为元组,因为我的真实数据集中的标签太长而无法手动输入(96 个国家/地区,每个国家/地区有 26 个部门)。我将尝试这里描述的 xlrd 包并报告结果:stackoverflow.com/questions/37403460/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2014-10-20
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
相关资源
最近更新 更多