【问题标题】:Pandas: cannot filter based on string equalityPandas:无法根据字符串相等性进行过滤
【发布时间】:2015-09-27 00:23:41
【问题描述】:

在 python 2.7、OSX 上使用 pandas 0.16.2。

我从这样的 csv 文件中读取数据帧:

import pandas as pd

data = pd.read_csv("my_csv_file.csv",sep='\t', skiprows=(0), header=(0))

data.dtypes 的输出是:

name       object
weight     float64
ethnicity  object
dtype: object

我期待名称和种族的字符串类型。但是我在 SO 上找到了为什么它们在较新的 pandas 版本中是“对象”的原因。

现在,我想根据种族选择行,例如:

data[data['ethnicity']=='Asian']
Out[3]: 
Empty DataFrame
Columns: [name, weight, ethnicity]
Index: []

data[data.ethnicity=='Asian']data[data['ethnicity']=="Asian"] 得到相同的结果。

但是当我尝试以下操作时:

data[data['ethnicity'].str.contains('Asian')].head(3)

我得到了我想要的结果。

但是,我不想使用“包含”- 我想检查直接相等。

请注意data[data['ethnicity'].str=='Asian'] 会引发错误。

我做错了吗?如何正确地做到这一点?

【问题讨论】:

  • 你的 df 中可能没有那个值,这就是它失败的原因,你确定你有那个确切的字符串吗?
  • 您的字符串数据是否包含一些前导和尾随的白色字符?
  • 发布data.loc[data['ethnicity'].str.contains('Asian'), 'ethnicity'].head(3).tolist()。它将帮助您查看字符串中是否有空格。
  • 以下两个答案都是正确的,它们解决了我的问题。事实证明,这是因为空格。很难在两个正确答案之间做出选择。我最终标记了更详细的答案。希望没关系。就像抛硬币一样。

标签: python string pandas filtering selection


【解决方案1】:

你的字符串中可能有空格,例如,

data = pd.DataFrame({'ethnicity':[' Asian', '  Asian']})
data.loc[data['ethnicity'].str.contains('Asian'), 'ethnicity'].tolist()
# [' Asian', '  Asian']
print(data[data['ethnicity'].str.contains('Asian')])

产量

  ethnicity
0     Asian
1     Asian

要从字符串中去除前导或尾随空格,您可以使用

data['ethnicity'] = data['ethnicity'].str.strip()

之后,

data.loc[data['ethnicity'] == 'Asian']

产量

  ethnicity
0     Asian
1     Asian

【讨论】:

    【解决方案2】:

    你可以试试这个:

    data[data['ethnicity'].str.strip()=='Asian']
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2014-08-30
      • 2021-03-30
      • 2015-02-26
      • 2019-02-04
      • 2022-11-29
      • 1970-01-01
      • 2015-08-06
      • 2017-12-23
      相关资源
      最近更新 更多