我已经在product_category和quantity_sold的基础上对dataframe(Dataframe)进行了排序。现在我想访问每个产品类别中销售最多的前两种产品,如何实现这一目标?我已经编写了一个for循环来访问它们,但是系统告诉我有一个关键错误,有人可以帮助我吗?谢谢!另外,如果它在dfDogNew中只有一个产品,那么它只会返回一行,假设如果我将切片设置为:2、熊猫会自动传递到下一个类别--在以前的cstegory中只有一个产品?
我将在下面附加我的for循环代码:
for i in product_category:
for g in dfDogNew['product_category']:
if i == g:
finaldf = dfDogNew[dfDogNew[g]].iloc[:2]
else:
pass我在前面的描述中列出了我所有的尝试。
发布于 2022-12-03 22:30:47
看起来,您正在尝试对DataFrame进行筛选,以便为product_category列的每个唯一值获取前两行。一种方法是使用DataFrame.groupby方法,它允许您按特定列对数据进行分组,然后向每个组应用一个函数。
在这种情况下,您可以将数据按product_category列分组,然后将DataFrame.head方法应用于每个组,以获得每个组的前两行。下面是一个如何做到这一点的例子:
# Group the data by the 'product_category' column
groups = dfDogNew.groupby("product_category")
# Apply the head method to each group to get the first two rows
finaldf = groups.head(2)返回的finaldf DataFrame将包含原始DataFrame中product_category列的每个唯一值的前两行。请注意,这种方法不需要for循环,而且通常比遍历DataFrame的行更有效。
如果只希望包含原始DataFrame中具有product_category值且存在于product_category数组中的行,则可以在对DataFrame进行分组之前使用DataFrame.isin方法对其进行筛选。例如:
# Filter the DataFrame to include only rows with a 'product_category'
# value that is present in the 'product_category' array
dfDogNew = dfDogNew[dfDogNew["product_category"].isin(product_category)]
# Group the data by the 'product_category' column
groups = dfDogNew.groupby("product_category")
# Apply the head method to each group to get the first two rows
finaldf = groups.head(2)这将只包括dfDogNew DataFrame中具有product_category数组中存在的product_category值的行,然后按上述方式对数据进行分组和筛选。
注意,当使用DataFrame.head方法时,如果一个组中的行少于两行,则生成的DataFrame将只包含可用的行。因此,如果product_category值在原始DataFrame中只有一行,则生成的finaldf DataFrame将只包含该类别的一行。你不需要担心分开处理这个案子。
https://stackoverflow.com/questions/74671202
复制相似问题