使用 pandas 查询按部分字符串选择行 [英] Select rows by partial string with query with pandas

查看:71
本文介绍了使用 pandas 查询按部分字符串选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame. 1列(name)具有字符串值.我想知道是否有一种方法可以使用

I have a DataFrame. 1 column (name) has string values. I was wondering if there was a way to select rows based on a partial string match against a particular column, using the DataFrame.query() method.

我尝试过:

  • df.query('name.str.contains("lu")').错误消息:"TypeError:'Series'对象是可变的,因此不能被散列"
  • df.query('"lu" in name').返回一个空的DataFrame.
  • df.query('name.str.contains("lu")'). Error message: "TypeError: 'Series' objects are mutable, thus they cannot be hashed"
  • df.query('"lu" in name'). Returns an empty DataFrame.

我使用的代码:

import pandas as pd

df = pd.DataFrame({
    'name':['blue','red','blue'],
    'X1':[96.32,96.01,96.05]
}, columns=['name','X1'])  


print(df.query('"lu" in name').head())
print(df.query('name.str.contains("lu")').head())

我知道我可以使用df[df['name'].str.contains("lu")],但是我更喜欢使用 查询.

I know I could use df[df['name'].str.contains("lu")] but I prefer to use query.

推荐答案

此答案已过期.请检查 @petobens的答案.

从0.20.2版开始,query不支持部分字符串匹配.对此有一个提出未来要求,其中一位核心开发人员似乎同意这将是一个很好的补充.

As of version 0.20.2, query doesn't support partial string matching. There is an open future request about it and one of the core developers seems to agree that it would be a nice addition.

这篇关于使用 pandas 查询按部分字符串选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆