【问题标题】:pandas select from Dataframe using startswith熊猫使用startswith从Dataframe中选择
【发布时间】:2022-05-10 03:54:39
【问题描述】:

这可行(使用 Pandas 12 开发版)

table2=table[table['SUBDIVISION'] =='INVERNESS']

然后我意识到我需要使用“开始于”来选择字段,因为我错过了一堆。 因此,根据 Pandas 文档,我尽我所能地尝试了

criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS'))
table2 = table[criteria]

得到 AttributeError: 'float' object has no attribute 'startswith'

所以我尝试了另一种结果相同的语法

table[[x.startswith('INVERNESS') for x in table['SUBDIVISION']]]

参考http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing 第 4 节:Series 的列表推导和 map 方法也可用于生成更复杂的标准:

我错过了什么?

【问题讨论】:

  • 你能举一个小例子来证明这一点吗,我很惊讶列表理解不会像地图一样提升......

标签: python numpy pandas


【解决方案1】:

您可以使用str.startswith DataFrame 方法给出更一致的结果:

In [11]: s = pd.Series(['a', 'ab', 'c', 11, np.nan])

In [12]: s
Out[12]:
0      a
1     ab
2      c
3     11
4    NaN
dtype: object

In [13]: s.str.startswith('a', na=False)
Out[13]:
0     True
1     True
2    False
3    False
4    False
dtype: bool

布尔索引可以正常工作(我更喜欢使用loc,但没有它也一样):

In [14]: s.loc[s.str.startswith('a', na=False)]
Out[14]:
0     a
1    ab
dtype: object

.

看起来系列/列中至少有一个元素是浮点数,它没有startswith方法,因此出现AttributeError,列表推导应该引发相同的错误......

【讨论】:

  • 感谢您的回复...似乎没有到达那里尝试了 table['SUBDIVISION']str.startswith('INVERNESS', na=False) 并得到了 table['SUBDIVISION' ]str.startswith('INVERNESS', na=False) ^ SyntaxError: invalid syntax 想知道我是否没有导入一些重要的东西?我不明白,因为我的直接 == 条件很好
  • 如果我尝试 table.loc[table['SUBDIVISION'].str.startswith('INVERNESS', na=False)] 我会得到一个很好的结果!但我仍然不明白之前的尝试有什么问题?
  • @dartdog 你少了一个点。请包括一小部分证明问题的数据(似乎很难相信:s)
  • 对不起,数据有 27 列长,即使发布剪辑也有点笨拙。我试过这个> table['SUBDIVISION'].str.startswith('INVERNESS',na='False') 和另一个'。'并且比较结果很糟糕(全部选择为假)我仍然不明白为什么我的原始语法失败了,因为我认为我正在关注文档。
  • @dartdog 大概只有 SUBDIVISION 列是相关的,所以只需粘贴它。
【解决方案2】:

检索所有startwith需要字符串的行

dataFrameOut = dataFrame[dataFrame['column name'].str.match('string')]

检索所有包含所需字符串的行

dataFrameOut = dataFrame[dataFrame['column name'].str.contains('string')]

【讨论】:

  • 当您可以使用str.startswith() 时,为什么要使用str.match() 函数来确定一个值是否以特定字符串开头? str.match() 用于将值与正则表达式进行匹配。如果您不需要正则表达式,则使用该函数可能会使您的代码变慢。
【解决方案3】:

对特定的列值使用startswith

df  = df.loc[df["SUBDIVISION"].str.startswith('INVERNESS', na=False)]

【讨论】:

    【解决方案4】:

    您可以使用apply 轻松地将任何字符串匹配函数应用于您的列元素。

    table2=table[table['SUBDIVISION'].apply(lambda x: x.startswith('INVERNESS'))]
    

    这假设您的“SUBDIVISION”列是正确的类型(字符串)

    编辑:修复缺少的括号

    【讨论】:

    • 这对我有用,一旦我添加了另一个右括号table2=table[table['SUBDIVISION'].apply(lambda x: x.startswith('INVERNESS')]]
    【解决方案5】:

    这也可以使用query来实现:

    table.query('SUBDIVISION.str.startswith("INVERNESS").values')
    

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2018-06-25
      • 1970-01-01
      • 2021-01-12
      相关资源
      最近更新 更多