【问题标题】:Group by and Filter with Pandas without loosing groupby在不丢失 groupby 的情况下使用 Pandas 进行分组和过滤
【发布时间】:2021-08-16 18:45:00
【问题描述】:

我是这个主题的初学者,到目前为止还没有找到任何可以帮助我的东西。 我正在努力对数据进行分组,然后使用我需要的值进行过滤。

就像这个例子,

我需要知道,例如,胡安买了多少辆红色汽车。 (红色汽车为每个客户销售)。 当我尝试时,我松开了组或过滤器,我不能两者都做。

有人可以帮我或建议一个帖子吗?

编辑1.

在社区的帮助下,我发现这是我的解决方案:

df = df.loc[:, df.columns.intersection(['Name', 'Car colour', 'Amount'])]

df = df.query('Car colour == Red')

df.groupby(['Name', 'Car colour'])['Amount'].sum().reset_index()

【问题讨论】:

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

如果您想考虑按名称和 Car_color 组销售的数量,请尝试

df.groupby(['Name', 'Car colour'])['Amount'].sum().reset_index()
#    Name   Car colour  Amount
 0    Juan      green       1
 1    Juan        red       3
 2  Wilson       blue       1
 3  carlos     yellow       1

【讨论】:

  • 你可以在groupby中传递as_index=False,即df.groupby(['Name', 'Car Color'], as_index=False)['Amount'].sum()
  • 我缺少的一点是在 groupby 之后通过 ['Amount'],谢谢!
【解决方案2】:

GroupBy.sum

df.groupby(['Name','Car Color']).sum()

输出:

import pandas as pd

data = {"Name": ["Juan", "Wilson", "Carlos", "Juan", "Juan", "Wilson", "Juan", "Carlos"],
        "Car Color": ["Red", "Blue", "Yellow", "Red", "Red", "Red", "Red", "Green"],
        "Amount": [24, 28, 40, 22, 29, 33, 31, 50]}
df = pd.DataFrame(data)
print(df)

【讨论】:

  • 谢谢!这是一种更简单的快速咨询方式。
【解决方案3】:

您可以通过将列名列表传递给groupby 函数来按多列分组,然后对每个组求和。

import pandas as pd

df = pd.DataFrame({'Name': ['Juan', 'Wilson', 'Carlos', 'Juan', 'Juan', 'Wilson', 'Juan'],
                   'Car Color': ['Red', 'Blue', 'Yellow', 'Red', 'Red', 'Red', 'Green'],
                   'Amount': [1, 1, 1, 1, 1, 1, 1]})
print(df)

agg_df = df.groupby(['Name', 'Car Color']).sum()
print(agg_df)

输出:

Name   Car Color        
Carlos Yellow          1
Juan   Green           1
       Red             3
Wilson Blue            1
       Red             1

请注意,生成的数据框有一个多索引,因此您可以通过将一组值传递给 loc 来获取 Juan 购买的红色汽车的数量。

cars = agg_df.loc[[('Juan', 'Red')]]
print(cars)

输出:

                Amount
Name Car Color        
Juan Red             3

【讨论】:

  • 谢谢!我很欣赏 .loc 函数的提示。
猜你喜欢
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 2022-01-25
  • 2018-03-04
  • 1970-01-01
  • 2023-02-10
  • 2013-07-30
  • 2022-11-03
相关资源
最近更新 更多