2017-06-20 391 views
0

我有一個三列的表格:A,BC。每列又分爲兩個子列:名稱規則如何從pandas DataFrame中提取子列?

我需要繪製出三個餅圖名稱子列使用matplotlib,但我不知道如何提取子列。這是我嘗試過,但沒有奏效:

chart = df['A'['Name']].value_counts().plot(kind='pie', labels=labels, autopct='%1.1f%%') 

回答

3

你可能想在Multiindexing和Slicing閱讀。

import pandas as pd 
import numpy as np 

arrays = [['A', 'A', 'B', 'B', 'C', 'C'], 
      ['Name', 'Rule', 'Name', 'Rule', 'Name', 'Rule']] 
tuples = list(zip(*arrays)) 
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) 
df = pd.DataFrame(np.random.rand(3, 6)*10, columns=index) 

#creates this dataframe: 
#first   A     B     C   
#second  Name  Rule  Name  Rule  Name  Rule 
#0  2.075001 4.702192 3.480122 1.785579 5.078655 9.053004 
#1  7.313122 3.762273 7.423559 8.713660 9.107358 5.643705 
#2  8.981356 9.748874 1.131691 1.487273 0.096690 6.175825 

# then index it with a none slice for the first column index and `"Name"` for the second. 

df.loc[:,(slice(None), 'Name')].plot(kind='pie', subplots=True, autopct='%1.1f%%') 

enter image description here

+0

感謝您的解決方案。我一直在試圖實現它,但得到一個錯誤「'MultiIndex Slicing要求索引完全是放大的元組len(2),lexsort depth(1)'」。你知道這個錯誤可以引用什麼嗎? 我有這個表中的字符串,而不是你使用np.random導入的數字。 – Nata

+0

我想你會明白,在不知道代碼的情況下幾乎不可能知道你有問題。 – ImportanceOfBeingErnest

+0

對不起,這是我的代碼。表中還有一些額外的列(Name2,Rule2),但我不需要它們進行繪圖。 'A','A','A', 'B','B','B','B', 'C','C',' 'Name','Rule','Name2','Rule2',' 'Name','Rule','Name2','Rule2','Name','Rule' ,'Name2','Rule2']] tuples = list(zip(* arrays)) index = pd.MultiIndex.from_tuples(元組,名稱= ['first','second']) df_new = pd。 DataFrame(df,columns = index) df_new.loc [:,(slice(None),'Name')]。plot(kind ='pie',subplots = True,labels = labels,autopct ='%1.1f %1')' – Nata

相關問題