[英]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.