Der Ansatz, an den ich denken kann, ist die Verwendung eines pivot_table
mit Rändern, um die Summen nach Stadt zu haben, wobei die Werte nach Gerät gehalten werden. Dann können Sie nach dem Rand sortieren, die Ränder löschen und dann den gestapelten Barplot plotten.
Hier ist der Code:
# 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);
Und hier ist das Ergebnis:
Der 'Schritt für Schritt' Datenaufbau ist die folgende:
# 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
alle Dann Sie müssen den gestapelten Barplot zeichnen.
Möchten Sie eine Aufteilung zwischen Mobil/Desktop für die meisten besuchten zählen oder nicht? –
@StevenG Ja, ich muss diesen Split aber sortieren nach Summe von Handy und Desktop – cooperok