简体   繁体   中英

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

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

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!

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