简体   繁体   中英

Select rows from a DataFrame based on last characters of values in a column in pandas

I want to select rows from columns with last word as 'oo' in Column A how can I do this.

I went through the link :- Select rows from a DataFrame based on values in a column in pandas

What I tried :-

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'])

This is giving me dataframe with entries

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

What should I try to get 5th row along with the other rows which I got? Expected Output :-

     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

我会这样:

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

您可以使用布尔运算符

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM