【问题标题】:Python IO Unhashable list RegexPython IO Unhashable 列表正则表达式
【发布时间】:2023-03-08 20:09:01
【问题描述】:

我有一个从 txt 文件加载的列表,并运行了一些代码来匹配数据。但是我得到了TypeError: Unhashable list 我在 Stack 上查看了几个答案,但找不到将列表传递到循环中的位置。我猜它与 df 有关,因为它在我不使用加载的数据时起作用。

import pandas as pd
import re

#Capture tester
df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['(?i)(C|F|L)at', 'Dog']


for i in xrange(len(patterns)):
    df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

print df

我也看不到将列表传递到for 循环的位置。

'patterntest.txt' 里面的所有文件都只是一些文本,例如:

dog
cat
mouse
frog
fox
canis sp

这是我的意见

import pandas as pd
import re

#Capture tester
df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['(?i)(C|H|L)at', 'Dog']




##
##for i in xrange(len(patterns)):
##    df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

print df.names.str.match(patterns[0])
print df.names.str.match(patterns[1])

输出:

>>> 
C:\Python27\lib\site-packages\pandas\core\strings.py:350: UserWarning: In future versions of pandas, match will change to always return a bool indexer.
  " always return a bool indexer.""", UserWarning)
0      []
1    (C,)
2      []
3      []
4      []
5      []
Name: names, dtype: object
0     True
1    False
2    False
3    False
4    False
5    False
Name: names, dtype: bool

我测试了这两种模式,看看它是否是正则表达式,看起来可能是。

更新:确认这是一个正则表达式问题,改成正则表达式,它工作正常。

df = pd.read_csv('patterntest.txt', header=None, dtype=str)
df.columns = ['names']
df['status']=''

patterns=['Cat', 'Dog']



for i in xrange(len(patterns)):
    df.loc[df.names.str.match(patterns[i]),'status'] = 'CAPTURED'

那么有没有办法解决这个问题?

【问题讨论】:

  • df.names.str.match(patterns[i]) 返回什么?
  • @NPE 如果我将模式手动放入其中,则会返回一堆 []。如果我输入pattern[1],它会返回一个布尔值。
  • @NPE 我认为这与数据帧的格式有关,因为df.names.str.match(patterns[1]) 返回一个True/False 值的数组。但是当你把它放入 df[df.names.str.match(patterns[1])] 时,你会得到括号 []
  • 你能举一个小例子来证明这一点吗?
  • @AndyHayden 是的,我会的

标签: python regex io pandas


【解决方案1】:

解释折旧(在 0.13 中)匹配的行为:它现在返回 bool 除非模式中有组 (这里括号是组,因此 C 在一个中返回行)... :s

您应该使用str.contains 而不是str.match*:

In [11]: s.str.contains('(?i)(C|H|L)at', flags=re.IGNORECASE)
Out[11]: 
0    False
1     True
2    False
3    False
4    False
5    False
Name: name, dtype: bool

In [12]: s.str.contains('Dog', flags=re.IGNORECASE)
Out[12]: 
0     True
1    False
2    False
3    False
4    False
5    False
Name: name, dtype: bool

要检查它是 整个 字符串,您应该使用开始 (^) 和结束 ($) 正则表达式:

In [13]: s.str.contains('^Dog$', flags=re.IGNORECASE)
Out[13]: 
0     True
1    False
2    False
3    False
4    False
5    False
Name: name, dtype: bool

* 注意:match is deprecated 在 0.13 中。

【讨论】:

  • str.contains 有效,但它也会获取不需要的数据(即:诸如“African Wild Dog”、“Super Cat”之类的字符串)
  • @user3084006 使用特殊的开始和结束正则表达式,例如'^Dog$'.
猜你喜欢
  • 2012-09-02
  • 1970-01-01
  • 2010-09-12
  • 2011-08-06
  • 2013-02-07
  • 2016-09-27
  • 2020-10-15
  • 1970-01-01
  • 2013-11-24
相关资源
最近更新 更多