根据DataFrame中的值计数保留前n个项的所有行

时间:2019-01-19 16:59:24

标签: python pandas dataframe

我是Python和Pandas的新手,在使用DataFrame s时遇到一些麻烦。

我在熊猫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

我想计算每种产品的购买频率,并将排名前n的产品保留在我的DataFrame中。我该怎么办?

例如,对于前n = 2个产品,结果将如下所示。

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

即,删除具有ProductC和ProductZ的行。

最后,我想按以下n个产品展示数据。

         ProductA    ProductB
XXX          1           1
YYY          1           1
ZZZ          1           1

我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要:

#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