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

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


我想统计购买每种产品的频率,并将前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


我将不胜感激。

最佳答案

你需要:

#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

关于python - 根据DataFrame中的值计数保留前n个项的所有行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54269358/

10-12 00:24
查看更多