79

这有效(使用 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 方法也可用于生成更复杂的标准:

我错过了什么?

4

4 回答 4

104

您可以使用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

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

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

.

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

于 2013-07-30T22:16:05.797 回答
25

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

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

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

dataFrameOut = dataFrame[dataFrame['column name'].str.contains('string')]
于 2018-03-25T16:31:34.860 回答
8

对特定列值使用startswith

df  = df.loc[df["SUBDIVISION"].str.startswith('INVERNESS', na=False)]
于 2020-01-21T05:25:54.300 回答
6

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

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

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

编辑:修复缺少的括号

于 2019-05-10T08:48:27.967 回答