Pandas使用startswith从数据帧中选择

2024-04-23 10:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这是可行的(使用Pandas 12 dev)

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

然后我意识到我需要用“开始于”来选择字段,因为我遗漏了一堆。 所以按照熊猫医生的说法,我尽可能的跟着他

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

并得到attributeRor:“float”对象没有属性“startswith”

所以我尝试了另一种语法

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

参考http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing 第4节:列表理解和系列地图法也可用于产生更复杂的标准:

我错过了什么?


Tags: lambdadevmappandastable医生意识criteria
3条回答

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

是的。

看起来序列/列中至少有一个元素是float,它没有startswith方法,因此AttributeError,list comprehension应该引起相同的错误。。。

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

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

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

编辑:修复缺少的括号

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

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

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

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

相关问题 更多 >