pandas使用startswith从Dataframe中选择

dar*_*dog 39 python numpy pandas

这工作(使用Pandas 12 dev)

table2=table[table['SUBDIVISION'] =='INVERNESS']
Run Code Online (Sandbox Code Playgroud)

然后我意识到我需要使用"开头"来选择字段因为我错过了一堆.所以按照我可以遵循的熊猫文档,我试过了

criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS'))
table2 = table[criteria]
Run Code Online (Sandbox Code Playgroud)

并得到了AttributeError:'float'对象没有属性'startswith'

所以我尝试了一种具有相同结果的替代语法

table[[x.startswith('INVERNESS') for x in table['SUBDIVISION']]]
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?

And*_*den 55

您可以使用str.startswithDataFrame方法提供更一致的结果:

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
Run Code Online (Sandbox Code Playgroud)

并且布尔索引将正常工作(我更喜欢使用loc,但它没有相同的工作原理):

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

.

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


Vin*_*san 22

检索以所需字符串开头的所有行

dataFrameOut = dataFrame[dataFrame['column name'].str.match('string')]
Run Code Online (Sandbox Code Playgroud)

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

dataFrameOut = dataFrame[dataFrame['column name'].str.contains('string')]
Run Code Online (Sandbox Code Playgroud)

  • 当您可以使用 str.startswith() 时,为什么要使用 str.match() 函数来确定值是否以特定字符串开头?`str.match()` 用于将值与正则表达式进行匹配。如果您不需要正则表达式,使用该函数 **_may_** 会使您的代码比所需的更慢。 (5认同)

Ale*_*e81 5

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

table2=table[table['SUBDIVISION'].apply(lambda x: x.startswith('INVERNESS'))]
Run Code Online (Sandbox Code Playgroud)

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

编辑:修复缺少的括号


Sau*_*abh 5

对特定列值使用开始

df  = df.loc[df["SUBDIVISION"].str.startswith('INVERNESS', na=False)]
Run Code Online (Sandbox Code Playgroud)