Q:

Preserving all rows with top n items based on value count in a DataFrame

I'm new to Python and Pandas and have some trouble in working with DataFrames.
I have the following data set in a Pandas DataFrame.
InvoiceId       StockCode      Price
XXX             ProductA       199,00
XXX             ProductB       78,00
XXX             ProductC       100,00
YYY             ProductB       78,00
YYY             ProductA       199,00
ZZZ             ProductA       199,00
ZZZ             ProductB       78,00

...             ...            ...

ZZZ             ProductY       19,00

I want to count how often each product was purchased and keep the top n products in my DataFrame. How can I do that?
For example, for the top n=2 products, the result would be as follows.
InvoiceId       StockCode      Price
XXX             ProductA       199,00
XXX             ProductB       78,00
YYY             ProductB       78,00
YYY             ProductA       199,00
ZZZ             ProductA       199,00
ZZZ             ProductB       78,00

I.e., the rows with ProductC and ProductZ were removed.
In the end, I want to present the data with the top n products as follows.
         ProductA    ProductB
XXX          1           1
YYY          1           1
ZZZ          1           1

I'd appreciate any help.

A:

You need:
#convert column to numeric
df['Price'] = df['Price'].str.replace(',','.').astype(float)

#get top2 values from index
print (df['Price'].value_counts().iloc[:2])
78.0     3
199.0    3
Name: Price, dtype: int64

#filter rows with top2 values (78, 199)
df = df[df['Price'].isin(df['Price'].value_counts().iloc[:2].index)]
print (df)
  InvoiceId StockCode  Price
0       XXX  ProductA  199.0
1       XXX  ProductB   78.0
3       YYY  ProductB   78.0
4       YYY  ProductA  199.0
5       ZZZ  ProductA  199.0
6       ZZZ  ProductB   78.0

#count top2
df1 = pd.crosstab(df['InvoiceId'],
                  df['StockCode'])
print (df1)
StockCode  ProductA  ProductB
InvoiceId                    
XXX               1         1
YYY               1         1
ZZZ               1         1

