Fix Python – How to filter rows containing a string pattern from a Pandas dataframe [duplicate]

Question

Asked By – John Knight

Assume we have a data frame in Python Pandas that looks like this:

df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']})

Or, in table form:

ids    vals
aball   1
bball   2
cnut    3
fball   4

How do I filter rows which contain the key word “ball?” For example, the output should be:

ids    vals
aball   1
bball   2
fball   4

Now we will see solution for issue: How to filter rows containing a string pattern from a Pandas dataframe [duplicate]


Answer

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids  vals
0  aball     1
1  bball     2
3  fball     4

This question is answered By – Amit

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0