0
我有一个三列的表格:A,B和C。每列又分为两个子列:名称和规则。如何从pandas DataFrame中提取子列?
我需要绘制出三个饼图名称子列使用matplotlib,但我不知道如何提取子列。这是我尝试过,但没有奏效:
chart = df['A'['Name']].value_counts().plot(kind='pie', labels=labels, autopct='%1.1f%%')
我有一个三列的表格:A,B和C。每列又分为两个子列:名称和规则。如何从pandas DataFrame中提取子列?
我需要绘制出三个饼图名称子列使用matplotlib,但我不知道如何提取子列。这是我尝试过,但没有奏效:
chart = df['A'['Name']].value_counts().plot(kind='pie', labels=labels, autopct='%1.1f%%')
你可能想在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%%')
感谢您的解决方案。我一直在试图实现它,但得到一个错误“'MultiIndex Slicing要求索引完全是放大的元组len(2),lexsort depth(1)'”。你知道这个错误可以引用什么吗? 我有这个表中的字符串,而不是你使用np.random导入的数字。 – Nata
我想你会明白,在不知道代码的情况下几乎不可能知道你有问题。 – ImportanceOfBeingErnest
对不起,这是我的代码。表中还有一些额外的列(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