[英]How to read multi index dataframe in python
这是我的 dataframe 叫 df
University Subject Colour
Melb Math Red
English Blue
Sydney Math Green
Arts Yellow
English Green
Ottawa Med Blue
Math Yellow
University 和 Subject 都是此 dataframe 的索引键
当我这样做时
print(df.to_dict('index'))
我明白了
{(Melb, Math): {'Colour': Red}, (Melb, English): {'Colour': Blue}, ...
当我这样做时
print(df["Colour"])
我明白了
University Subject Colour
Melb Math Red
English Blue
Sydney Math Green
Arts Yellow
English Green
Ottawa Med Blue
Math Yellow
当我做
print(df["University"])
我收到一个错误
KeyError: 'University'
我想要的是一种分别读取每个值的方法
我想读大学,另一篇读主题,第三篇读颜色
怎么做?
更快的方法是使用 python 的zip function,这种方法比手动运行 for 循环要快得多。
university_list = list(zip(*df.index))[0]
subject_list = list(zip(*df.index))[1]
colour_list = list(df['Colour'])
index_list = list(zip(*df.index))
Output:
[('Melb','Sydney','Ottawa'),('Math','English','Math','Arts',...)]
您将获得一个元组列表,其中每个元组都与一个索引列相关。
(列将按从左到右的顺序排列:例如第一个索引列将是第一个元组,第二个索引列将是第二个元组,依此类推!)
现在,要获得单独的索引列列表,您可以简单地做,
Universities = list(index_list[0]) #this will give you separate list for university ('Melb','Sydney','Ottawa')
Subjects = list(index_list[1]) #this will give you separate list for Subjects ('Math','English','Math','Arts',...)
你可以通过简单地做到这一点,
column_data = list(df['column_name'])
#which in your case will be
colour_list = list(df['Colour'])
现在,想象一个情况,您需要整个 Dataframe 作为元组列表,其中每个元组将具有一列数据。 (包括索引列)
列表看起来像,
[(Col-1_data, ,...),(Col-2_data, ,...),...]
要实现这样的事情,您将不得不重新设置索引、获取数据并再次设置索引。 下面的代码将完成任务,
index_names = list(df.index.names) #saving current indexes so that we can reassign them later.
df.reset_index(inplace = True)
dataframe_raw_list = df.values.tolist() #This will be a list of tuples where each tuple is a row of dataframe
df.set_index(index_names, inplace = True)
dataframe_columns_list = list(zip(*dataframe_raw_list)) #This will be a list of tuples where each tuple is a Column of dataframe
Output :
[(Col-1_data, ,...),(Col-2_data, ,...),...]
您可以通过以下方式获得索引的第一级(“大学”):
[i[0] for i in df.index]
同样对于第二级(“主题”)
[i[1] for i in df.index]
此外,如果您只想获取“颜色”列的值,可以使用:
list(df['Colour'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.