简体   繁体   中英

python string contains and string is equal to

I have this r code that I need to translate to python. so for grepl, I would use the str.contains but can I add str is equal to in the same line? basically, how would you put this in one sentence?

rank <- subset(rankings, grepl("o",type) | grepl("v",type) | grepl("fs",type) 
                   | type == "kp" |  type == "paa" | type == "tb" | type== "ts, thumb")

One method would be to join the list of patterns with | , use that in contains on the 'type' column, OR ( | ) use the isin for fixed string match on a list of elements

rankings[(rankings['type'].isin(['kp', 'paa', 'tb', 'ts, thumb'])) |
          (rankings['type'].str.contains("|".join(["v", "fs", "o"])))] 

-output

#   type
#0  kp
#2  paa
#3  tb
#5  ts, thumb
#7  v1
#8  fs2
#9  orange

In R , the OP's code can be simplified as

subset(rankings, grepl("o|v|fs", type)| 
             type %in% c("kp", "paa", "tb", "ts, thumb"))

data

import pandas as pd
rankings = pd.DataFrame({"type":["kp", "5g", "paa", "tb", "ta", "ts, thumb", "ta1", "v1", "fs2", "orange", "efz"]})

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