Ich habe folgende Pandas Datenrahmen:Werte ändern in Pandas Datenrahmen nach value_counts()
import pandas as pd
from pandas import Series, DataFrame
data = DataFrame({'Qu1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'],
'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'banana', 'banana'],
'Qu3': ['apple', 'potato', 'sausage', 'cheese', 'cheese', 'potato', 'cheese', 'potato', 'egg']})
Ich mag würde Werte in Spalten ändern Qu1
, Qu2
, Qu3
nach value_counts()
, wenn der Zählwert groß oder gleich einige Anzahl
zum Beispiel für Qu1
Spalte
>>> pd.value_counts(data.Qu1) >= 2
cheese True
potato True
banana True
apple False
egg False
Ich möchte Werte cheese
, potato
, banana
behalten, weil jeder Wert mindestens zwei Erscheinungen hat.
Von Werte apple
und egg
Ich möchte Wert others
Für Qu2
keine Änderungen Spalte erstellen:
>>> pd.value_counts(data.Qu2) >= 2
banana True
apple True
sausage True
das Endergebnis wie in test_data
angebracht
test_data = DataFrame({'Qu1': ['other', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'other'],
'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'banana', 'banana'],
'Qu3': ['other', 'potato', 'other', 'cheese', 'cheese', 'potato', 'cheese', 'potato', 'other']})
Dank!
ein bisschen mehr elegant und schneller als mein Ansatz mit '.replace()'! – Stefan
@StefanJansen Danke. :) Meiner Erfahrung nach ist '.replace()' im Allgemeinen langsamer als '.map()', also neige ich dazu, Map zu verwenden, wenn beides möglich ist.Obwohl ich immer noch denke, dass die Kombination apply-map-value_counts die Dinge wiederholen kann, konnte ich keine bessere Alternative finden. – ayhan
Danke! Elegante Lösung. Wie funktioniert das '.where() mit> = 2'? – Toren