python - Pandas 数据透视表 : String and Integer filter

标签 python pandas filter pivot-table

我正在尝试在我的数据透视表构建器上实现一个过滤器,生成一个表:table,它可以过滤掉两个整数(<、<=、>、>=、= 和 !=)和字符串值(!=,=)根据用户规范:

attribute = raw_input('Attribute to filter: ')
conditional = raw_input('Conditional to filter by: ')
limit = raw_input('Value to filter by: ')

如果我通过执行以下操作选择的属性由整数组成,则过滤器将起作用(如果不需要过滤器,则建议输入“所有值”):

if attribute != "sAtt1" and attribute != "sAtt2" and attribute != "sAtt3":
    limit = int(limit)

if conditional != "All Values" or conditional != "all values":
    if conditional == "!=":
        table = table[table[attribute] != limit]
    elif conditional == "=":
        table = table[table[attribute] = limit]

其余条件依此类推。

但是,当属性由字符串组成时,这不起作用。

sAtt1、sAtt2 和 sAtt3 是由字符串组成的属性(我希望保持不变),但是当(例如)使用 sAtt1 时,会发生以下错误:

KeyError: "sAtt1"

这让我很困惑,因为包含错误的属性不会返回此错误 - 有什么想法 KeyError 是从哪里来的吗?

编辑

这是我一直在测试的数据示例(列包含字符串和整数):

https://www.dropbox.com/s/gyvho9cmxqx4nta/Football.csv?dl=0

最佳答案

选项 1
我会构建一个操作 map

op_map = {
    '<': pd.Series.lt,
    '<=': pd.Series.le,
    '>': pd.Series.gt,
    '>=': pd.Series.ge,
    '==': pd.Series.eq,
    '!=': pd.Series.ne
}

然后你可以像这样使用它:

op_map[conditional](table[attribute], limit)
<小时/>

选项 2
您还可以构建一个查询字符串。但您将无法使用 =

table.query('@attribute @conditional @limit`)

关于python - Pandas 数据透视表 : String and Integer filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44185331/

相关文章:

从 valgrind 的 callgrind 输出过滤对 libc 的调用

c - 哪些 DSP 滤波器算法易于实现?

python - 基于另一列复制行

python - scipy cephes 导入错误

python - 通过与其他 Dataframe 列映射来更改 Dataframe 列名称,Python 3.6

python - Pandas Dataframe 到所需的 python 字典

python - 我的腌制 cookies 在 selenium - python 中不起作用?

python - python3 十六进制的奇怪行为

python - 如果满足条件, Pandas 会创建一列等于另一列

javascript - 通过数组值从集合中获取项目