首页 \ 问答 \ 将多个过滤器应用于大熊猫DataFrame或Series的高效方法(Efficient way to apply multiple filters to pandas DataFrame or Series)

将多个过滤器应用于大熊猫DataFrame或Series的高效方法(Efficient way to apply multiple filters to pandas DataFrame or Series)

我有一个场景,用户想要将几个过滤器应用于Pandas DataFrame或Series对象。 基本上,我想有效地将​​用户运行时指定的一堆过滤(比较操作)链接在一起。

过滤器应该是添加剂(也就是每个应用都应该缩小结果)。

我正在使用reindex()但是每次都会创建一个新对象,并复制底层数据(如果我正确理解文档)。 因此,过滤大型系列或DataFrame时,效率可能非常低。

我在想,使用apply()map()或类似的东西可能会更好。 我对熊猫来说很新,尽管如此,仍然试图围绕着一切。

TL; DR

我想使用以下表单的字典,并将每个操作应用于给定的Series对象并返回一个“已过滤”的系列对象。

relops = {'>=': [1], '<=': [1]}

长例子

我将从一个目前的例子开始,只是过滤一个单一的系列对象。 以下是我目前使用的功能:

   def apply_relops(series, relops):
        """
        Pass dictionary of relational operators to perform on given series object
        """
        for op, vals in relops.iteritems():
            op_func = ops[op]
            for val in vals:
                filtered = op_func(series, val)
                series = series.reindex(series[filtered])
        return series

用户提供一个字典与他们要执行的操作:

>>> df = pandas.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]})
>>> print df
>>> print df
   col1  col2
0     0    10
1     1    11
2     2    12

>>> from operator import le, ge
>>> ops ={'>=': ge, '<=': le}
>>> apply_relops(df['col1'], {'>=': [1]})
col1
1       1
2       2
Name: col1
>>> apply_relops(df['col1'], relops = {'>=': [1], '<=': [1]})
col1
1       1
Name: col1

再次,我上述方法的“问题”是我认为有可能不必要的复制数据的中间步骤。

此外,我想扩展这个,以便传入的字典可以包括列操作符,并根据输入字典过滤整个DataFrame。 但是,我假设为Series可以轻松扩展到DataFrame。


I have a scenario where a user wants to apply several filters to a Pandas DataFrame or Series object. Essentially, I want to efficiently chain a bunch of filtering (comparison operations) together that are specified at run-time by the user.

The filters should be additive (aka each one applied should narrow results).

I'm currently using reindex() but this creates a new object each time and copies the underlying data (if I understand the documentation correctly). So, this could be really inefficient when filtering a big Series or DataFrame.

I'm thinking that using apply(), map(), or something similar might be better. I'm pretty new to Pandas though so still trying to wrap my head around everything.

TL;DR

I want to take a dictionary of the following form and apply each operation to a given Series object and return a 'filtered' Series object.

relops = {'>=': [1], '<=': [1]}

Long Example

I'll start with an example of what I have currently and just filtering a single Series object. Below is the function I'm currently using:

   def apply_relops(series, relops):
        """
        Pass dictionary of relational operators to perform on given series object
        """
        for op, vals in relops.iteritems():
            op_func = ops[op]
            for val in vals:
                filtered = op_func(series, val)
                series = series.reindex(series[filtered])
        return series

The user provides a dictionary with the operations they want to perform:

>>> df = pandas.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]})
>>> print df
>>> print df
   col1  col2
0     0    10
1     1    11
2     2    12

>>> from operator import le, ge
>>> ops ={'>=': ge, '<=': le}
>>> apply_relops(df['col1'], {'>=': [1]})
col1
1       1
2       2
Name: col1
>>> apply_relops(df['col1'], relops = {'>=': [1], '<=': [1]})
col1
1       1
Name: col1

Again, the 'problem' with my above approach is that I think there is a lot of possibly unnecessary copying of the data for the in-between steps.

Also, I would like to expand this so that the dictionary passed in can include the columns to operator on and filter an entire DataFrame based on the input dictionary. However, I'm assuming whatever works for the Series can be easily expanded to a DataFrame.


原文:https://stackoverflow.com/questions/13611065
更新时间:2023-06-12 09:06

最满意答案

你不应该使用go run来运行你的Go程序。 你应该用go build来编译它,然后用Upstart来运行它。

改用exec /path/to/your/binary

另请参阅: - 无法通过Upstart启动Golang Prog - https://coderwall.com/p/iekaog - https://groups.google.com/forum/m/#!topic/golang-nuts/uBrN-G7anKg (很多例子)


You shouldn't be using go run to run your Go program. You should compile it with go build and then use Upstart to run that.

Use exec /path/to/your/binary instead.

Also see: - Can't Start Golang Prog Via Upstart - https://coderwall.com/p/iekaog - https://groups.google.com/forum/m/#!topic/golang-nuts/uBrN-G7anKg (lots of examples)

相关问答

更多
  • 从您提到的Upstart中,我将假设这个问题是针对在Ubuntu服务器上运行的服务的。 在Ubuntu服务器上,新兴的工作对于创建始终开启的服务来说是最简单和最方便的选择,可以在正确的时间启动,并且可以用熟悉的命令停止或重新加载。 要创建一个新贵的服务,你需要在/etc/init添加一个文件。 称为.conf 。 一个示例脚本如下所示: description "My chat server" author "your@email-address.com" start on r ...
  • 你不应该使用go run来运行你的Go程序。 你应该用go build来编译它,然后用Upstart来运行它。 改用exec /path/to/your/binary 。 另请参阅: - 无法通过Upstart启动Golang Prog - https://coderwall.com/p/iekaog - https://groups.google.com/forum/m/#!topic/golang-nuts/uBrN-G7anKg (很多例子) You shouldn't be using go run ...
  • 我废弃了AWS EC2实例并使用Ubuntu 14.04实现重新创建它,我将其升级到16.04。 我严格遵循这里的指导 http://codepany.com/blog/rails-5-puma-capistrano-nginx-jungle-upstart/ 以及来自同一博客的相关链接。 现在Nginx和Puma正在一起工作,我的应用程序在这里完美运行: http://ec2-54-159-156-217.compute-1.amazonaws.com/ 指南的唯一区别是我保留了数据库的AWS RDS ...
  • 我猜你使用Brew来安装Node,所以这里的指南可能是有用的http://madebyhoundstooth.com/blog/install-node-with-homebrew-on-os-x/ 。 您需要确保npm / bin在您的路径中,因为它描述export PATH="/usr/local/share/npm/bin:$PATH" 。 这是npm将为已安装的软件包安装bin存根的位置。 纳米版本也将按照这里所述的方式工作http://architectryan.com/2012/10/02/ad ...
  • 你可以试试这个(我必须把我的git pull包装在sudo中才能工作?): start on runlevel [12345] respawn pre-start script export HOME="/home/user" cd $HOME/scripts/ exec sudo -u user git pull end script script export HOME="/home/user" cd $HOME/commands/ exec sudo -u user sv ...
  • upstart进程由内核在系统引导时执行。 您可以使用内核命令行参数配置内核使用的命令。 它应该如下所示: init=/sbin/init --logdir=/path/to/logfiles 虽然您可以配置grub将该命令行选项传递给内核,但您也可以使用简单的包装器脚本。 将原始init二进制文件复制到备份: sudo cp /sbin/init{,.orig} 然后创建包装脚本: / sbin / init : #!/bin/bash # Pass modified logdir option i ...
  • 在搜索互联网寻求解决方案之后,我们决定坚持使用nodejs而不是永远用于此任务。 它更容易,并且通过重生它可以完成我们需要永远为我们做的一切。 start on runlevel [2345] stop on shutdown respawn script exec sudo nodejs /usr/lib/sites/path/Node/ourapp.js 2>&1 >> /var/log/ourapp.log end script After scouring the internet ...
  • 我发现了这个问题。 说明如下, 启动时的root用户将首先su - 进入rails用户(在本例中为'joe')然后执行bundle以启动unicorn。 rbenv是单用户,只有'joe'安装了bundle。 bundle的路径可能存储在我的.bashrc文件中。 但是.bashrc文件不是通过su登录而调用的 - 并且导致bundle未安装错误。 我在.profile中包含了与rbenv相关的路径。 这种方式当root su - into'joe'时,路径被加载。 I found out the issu ...
  • 我最终通过将节点和npm文件从一个droplet复制到另一个droplet来实现它: scp -r /usr/local/bin/. root@0.0.0.0:/usr/local/bin 现在我知道这是非常贫民窟,可能不是正确的方式,所以我仍然坚持正确的答案。 谢谢。 I ended up getting it work by copying the node and npm files from one droplet to another: scp -r /usr/local/bin/. root@0 ...
  • 您正在删除包含printenv的bin目录。 这应该说明一下: docker run -it --rm -w "/srv" microsoft/aspnetcore-build sh -c 'printenv; rm -rf ../**/bin; printenv' You are deleting the bin dir that contains printenv. This should illustrate it: docker run -it --rm -w "/srv" microsoft/as ...

相关文章

更多

最新问答

更多
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的
  • SimplePie问题(SimplePie Problem)
  • 在不同的任务中,我们可以同时使用多少“上下文”?(How many 'context' we can use at a time simultaneously in different tasks?)
  • HTML / Javascript:从子目录启用文件夹访问(HTML/Javascript: Enabling folder access from a subdirectory)
  • 为什么我会收到链接错误?(Why do I get a linker error?)
  • 如何正确定义析构函数(How to properly define destructor)
  • 垂直切换菜单打开第3级父级。(Vertical toggle menu 3rd level parent stay opened. jQuery)
  • 类型不匹配 - JavaScript(Type mismatch - JavaScript)
  • 为什么当我将模型传递给我的.Net MVC 4控制器操作时,它坚持在部分更新中使用它?(Why is it that when I pass a Model to my .Net MVC 4 Controller Action it insists on using it in the Partial Update?)
  • 在使用熊猫和statsmodels时拉取变量名称(Pulling variable names when using pandas and statsmodels)
  • 如何开启mysql计划事件
  • 检查数组的总和是否大于最大数,反之亦然javascript(checking if sum of array is greater than max number and vice versa javascript)
  • 使用OpenGL ES绘制轮廓(Drawing Outline with OpenGL ES)
  • java日历格式(java Calendar format)
  • Python PANDAS:将pandas / numpy转换为dask数据框/数组(Python PANDAS: Converting from pandas/numpy to dask dataframe/array)
  • 如何搜索附加在elasticsearch索引中的文档的内容(How to search a content of a document attached in elasticsearch index)
  • LinQ to Entities:做相反的查询(LinQ to Entities: Doing the opposite query)
  • 从ExtJs 4.1商店中删除记录时会触发哪些事件(Which events get fired when a record is removed from ExtJs 4.1 store)
  • 运行javascript后如何截取网页截图[关闭](How to take screenshot of a webpage after running javascript [closed])
  • 如何使用GlassFish打印完整的堆栈跟踪?(How can I print the full stack trace with GlassFish?)
  • 如何获取某个exe应用程序的出站HTTP请求?(how to get the outbound HTTP request of a certain exe application?)
  • 嗨,Android重叠背景片段和膨胀异常(Hi, Android overlapping background fragment and inflate exception)
  • Assimp详细说明typedef(Assimp elaborated type refers to typedef)
  • 初始化继承类中不同对象的列表(initialize list of different objects in inherited class)
  • 使用jquery ajax在gridview行中保存星级评分(Save star rating in a gridview row using jquery ajax)
  • Geoxml3 groundOverlay zIndex(Geoxml3 groundOverlay zIndex)