Python Pandas - df.loc - 添加附加条件不起作用

标签 python pandas

我有一个包含以下代码的脚本,它按预期工作

Table2 = df.loc[df.Date.between('2018-11-22','2018-11-30')].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum()

但是,现在我尝试添加一个附加条件,以便过滤名为“region”的列,该列在数据集中具有值 Canada,但它似乎不起作用。

Table2 = df.loc[df.Date.between('2018-11-22','2018-11-30'), df['Region'] = 'Canada'].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum()

附加过滤器似乎没有影响。任何人都可以帮忙。谢谢

最佳答案

正如@Alaxander 提到的

这是一个示例片段:

import pandas

df = pd.DataFrame({
    "A": [1,2,3],
    "B": [4,5,6],
    "C": [1,1,1]
})

df.loc[((d["A"]==1) & (d["B"]==4)), ["A", "B"]]

此外,您可能想查看 df["Region"] = "Canada" 中使用的赋值运算符,它不应该是 == 吗用作过滤器?我也已将其添加到下面的代码中。

如果您想要特定字段,您的代码:

Table2 = df.loc[((df.Date.between('2018-11-22','2018-11-30')) & (df['Region'] == 'Canada')), ["Date", "Region"]].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum()

如果您想要所有字段,您的代码:

Table2 = df.loc[((df.Date.between('2018-11-22','2018-11-30')) & (df['Region'] == 'Canada'))].groupby(df['FPYear'])[['New Customer', 'Existing Customer', 'revenue']].sum()

PS:感谢@Alexander 提到这个错误。

关于Python Pandas - df.loc - 添加附加条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113106/

相关文章:

python - 为什么 Python 请求总是给我这个错误? "An existing connection was forcibly closed by the remote host"

python - 通过 DataFrame 设置 pandas DataFrame 的子集

python - 使用 Python 中的 Pandas 模块将从网站提取的项目写入具有不同长度列表的 .xls 工作表

python - Pandas :一列的累计总和基于另一列的值

python - Python sort() 函数有哪些参数?

python - urllib.request.urlopen 不接受带空格的查询字符串

python - 使用分组的键列创建两个 pandas 数据帧的 'differences' 结果集

python - Pandas Python 中 Timedeltas 列的总和

python - Pandas 中的多个直方图

python - 按任意间隔对时间索引的 DataFrame 进行分组