根据pandas中列的最后一个字符值从DataFrame中选择行

时间:2017-03-26 01:34:52

标签: python python-3.x pandas

我想从列中选择最后一个单词的行作为' oo'在A栏中我该怎么做。

我浏览了以下链接: - Select rows from a DataFrame based on values in a column in pandas

我尝试了什么: -

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo baroo foos bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  baroo    two  5  10
# 6  foos    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

这给了我带有条目的数据框

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
7  foo  three  7  14

我应该尝试将第五行与其他行一起获得? 预期产出: -

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
5  baroo    two  5  10
7  foo  three  7  14

2 个答案:

答案 0 :(得分:4)

我这样做:

df[df.A.str.endswith('oo')]

答案 1 :(得分:0)

您可以使用布尔运算符

print(df.loc[( df.A == 'foo')|(df.A =='baroo') , :])