我正在尝试绘制有关该地区5个地区的特定行业中家庭收入所占比例的信息。
我使用groupby按地区对数据框中的信息进行排序:
df = df_orig.groupby('District')['Portion of income'].value_counts(dropna=False)
df = df.groupby('District').transform(lambda x: 100*x/sum(x))
df = df.drop(labels=math.nan, level=1)
ax = df.unstack().plot.bar(stacked=True, rot=0)
ax.set_ylim(ymax=100)
display(df.head())
District Portion of income
A <25% 12.121212
25 - 50% 9.090909
50 - 75% 7.070707
75 - 100% 2.020202
由于此收入属于类别,因此我想以合理的方式对堆叠栏中的元素进行排序。产生的 Pandas 图如下。现在,排序(从每个栏的底部开始)为:
我意识到这些字母是按字母顺序排序的,并且很好奇是否可以设置自定义顺序。为了直观起见,我希望顺序是(再次从栏的底部开始):
然后,我想翻转图例以显示此顺序的相反顺序(即,我希望图例在顶部具有75-100,因为这将在条的顶部)。
参考方案
要将自定义排序顺序强加于收入类别,一种方法是将其转换为CategoricalIndex
。
要反转matplotlib图例条目的顺序,请使用以下SO问题中的get_legend_handles_labels
方法:Reverse legend order pandas plot
import pandas as pd
import numpy as np
import math
np.random.seed(2019)
# Hard-code the custom ordering of categories
categories = ['unsure', '<25%', '25 - 50%', '50 - 75%', '75 - 100%']
# Generate some example data
# I'm not sure if this matches your input exactly
df_orig = pd.DataFrame({'District': pd.np.random.choice(list('ABCDE'), size=100),
'Portion of income': np.random.choice(categories + [np.nan], size=100)})
# Unchanged from your code. Note that value_counts() returns a
# Series, but you name it df
df = df_orig.groupby('District')['Portion of income'].value_counts(dropna=False)
df = df.groupby('District').transform(lambda x: 100*x/sum(x))
# In my example data, np.nan was cast to the string 'nan', so
# I have to drop it like this
df = df.drop(labels='nan', level=1)
# Instead of plotting right away, unstack the MultiIndex
# into columns, then convert those columns to a CategoricalIndex
# with custom sort order
df = df.unstack()
df.columns = pd.CategoricalIndex(df.columns.values,
ordered=True,
categories=categories)
# Sort the columns (axis=1) by the new categorical ordering
df = df.sort_index(axis=1)
# Plot
ax = df.plot.bar(stacked=True, rot=0)
ax.set_ylim(ymax=100)
# Matplotlib idiom to reverse legend entries
handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels))
python pandas:按行对条件进行分组 - python
我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…
Python Pandas:按分组分组,平均? - python我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…
Python Pandas:在多列上建立布尔索引 - python尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…
Python-Excel导出 - python我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…
python :安装 python 后,如何导入 Pandas - python我已经安装了 python 。现在,当我尝试跑步时import pandas as pd 我收到以下错误Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandasFile ImportError: …