Ich habe einen Datenrahmen wie unten gezeigt.
type item
new apple
new apple
new io
new io
old apple
old io
old io
old se
old pj
etc el
Ich muss einen neuen Datenrahmen basierend auf Anzahl und eindeutiger Anzahl erstellen
type type_count unique_item_count
new 4 2
old 5 4
etc 1 1
col 'type_count' basiert auf der Häufigkeit von Beschriftungen in col'type 'col' unique_item_count 'basiert auf der eindeutigen Anzahl von Beschriftungen in col'item' für jedes eindeutige Etikett in col'type '.
auch wenn ich eine neue Spalte hinzufüge
type item val
new apple 20
new apple 6
new io 5
new io 6
old apple 5
old io 6
old io 4
old se 5
old pj 3
etc el 2
und möchte einen neuen Datenrahmen mit
type type_count unique_item_count total_count
new 4 2 37
old 5 4 23
etc 1 1 2
col 'total_count' ist die Summe der im col'val 'vorhandenen Beträge für jeden Typ
Verwendung DataFrameGroupBy.agg
mit Liste der Tupel - erster Wert gibt neuen Spaltennamen und zweite Aggregatfunktion an, hier size
und nunique
:
L = [('type_count','size'), ('unique_item_count','nunique')]
df = df.groupby('type', sort=False)['item'].agg(L).reset_index()
print (df)
type type_count unique_item_count
0 new 4 2
1 old 5 4
2 etc 1 1
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen