0

I am trying to rewrite the following in one line using list comprehension. I want to select cells that contains substring '[edit]' only. ut is my dataframe and the column that I want to select from is 'col1'. Thanks!

    for u in ut['col1']:
        if '[edit]' in u:
            print(u)

I expect the following output:
Alabama[edit]
Alaska[edit]
Arizona[edit]
...
  • See [this answer](https://stackoverflow.com/a/55335207/4909087), scroll down to "A Great Alternative: Use List Comprehensions!" – cs95 Apr 14 '19 at 18:44
  • @ChrisA I tried that and i got a syntax error. i think it has to do with the ordering of 'u in ut['col1'] with the list comprehension – peekabo Apr 15 '19 at 19:09

1 Answers1

0

If the output of a Pandas Series is acceptable, then you can just use .str.contains, without a loop

s = ut[ut["col1"].str.contains("edit")]

If you need to print each element of the Series separately, then loop over the Series using

for i in s:
    print(i)
edesz
  • 11,756
  • 22
  • 75
  • 123