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.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
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)
您可以apply
轻松地将任何字符串匹配函数应用于您的列元素。
table2=table[table['SUBDIVISION'].apply(lambda x: x.startswith('INVERNESS'))]
Run Code Online (Sandbox Code Playgroud)
这假设您的“SUBDIVISION”列是正确的类型(字符串)
编辑:修复缺少的括号
对特定列值使用开始
df = df.loc[df["SUBDIVISION"].str.startswith('INVERNESS', na=False)]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42512 次 |
最近记录: |