我可以考虑的方法是使用带有边距的pivot_table
,以按城市计算总值。然后,您可以按边距排序,删除边距,然后绘制堆叠的条形图。
下面的代码:
# Creates the DataFrame
df = pd.DataFrame({
'city':['New York', 'New York', 'Chicago', 'Detroit', 'Detroit'],
'device': ['desktop', 'mobile', 'desktop', 'desktop', 'mobile'],
'session_count': [10, 9, 6, 16, 7]
})
# Creates a pivot table with margins named 'All'
# Sorts by 'All' column
# Drops the margins
# Plots the stacked barplot
df.pivot_table(columns='device',
index='city',
values='session_count',
aggfunc=sum,
margins=True).\
sort_values(by='All', ascending=False).\
drop('All').drop('All', axis=1).\
plot.bar(stacked=True);
而这里的结果:
的 '一步一步' 的数据结构如下:
# Creates the DataFrame
df = pd.DataFrame({
'city':['New York', 'New York', 'Chicago', 'Detroit', 'Detroit'],
'device': ['desktop', 'mobile', 'desktop', 'desktop', 'mobile'],
'session_count': [10, 9, 6, 16, 7]
})
print(df)
# city device session_count
# 0 New York desktop 10
# 1 New York mobile 9
# 2 Chicago desktop 6
# 3 Detroit desktop 16
# 4 Detroit mobile 7
print(df.pivot_table(columns='device',
index='city',
values='session_count',
aggfunc=sum,
margins=True))
# device desktop mobile All
# city
# Chicago 6.0 NaN 6.0
# Detroit 16.0 7.0 23.0
# New York 10.0 9.0 19.0
# All 32.0 16.0 48.0
print(df.pivot_table(columns='device',
index='city',
values='session_count',
aggfunc=sum,
margins=True).\
sort_values(by='All', ascending=False))
# device desktop mobile All
# city
# All 32.0 16.0 48.0
# Detroit 16.0 7.0 23.0
# New York 10.0 9.0 19.0
# Chicago 6.0 NaN 6.0
print(df.pivot_table(columns='device',
index='city',
values='session_count',
aggfunc=sum,
margins=True).\
sort_values(by='All', ascending=False).\
drop('All').drop('All', axis=1))
# device desktop mobile
# city
# Detroit 16.0 7.0
# New York 10.0 9.0
# Chicago 6.0 NaN
然后,所有你必须做的是绘制堆叠的barplot。
你想在移动/桌面之间进行拆分访问次数吗? –
@StevenG是的,我需要保持这种分裂,但通过移动和桌面的总和 – cooperok