How to create a new dataframe from existing dataframe with certain condition - python

Viewed 4629

I have a dataframe looks like below.

   text      country    language
-----------------------------------
  football     US         Eng
  baseball     JP         Jpn
  swimming     UK         Eng
  running      FR         Fra
  rugby        NZ         Eng
  Hockey       NL         Dut

In python, I want to extract rows which contain strings 'ball' and 'ing' in the column 'text' and make a new dataframe with those rows like below.

   text      country    language
-----------------------------------
  football     US         Eng
  baseball     JP         Jpn
  swimming     UK         Eng
  running      FR         Fra
1 Answers

Using pandas, you can slice using multiple conditions, just watch out for tricky parenthesis on the syntax.

df = pd.DataFrame({'A': ['foo', 'bar', 'fooing', 'barball'],
                   'B': [1, 2, 3, 4]})

df_slice = df[(df.A.str.contains('ing')) | (df.A.str.contains('ball'))]

That should yield

df_slice
A        B
fooing   3
barball  4

If your goal is to slice in words that end in ing or ball, use endswith() instead of contains() in the conditions. Hope it helps!

Related