简体   繁体   中英

How to slice DataFrame using logical(“or”) and for loop in python?

I am a very beginner of Python.

The goal is to slice the column of DataFrame('incen') which contains specific device codes...

But the device codes keep changed, so I made it into a list('device_code').

I tried to use for loop like this way:

for a in device_code:
     incen[(incen.device_name.str.contains(a) == True)]

However, it couldn't be merged into one DataFrame.

So I solved it into this way which is super inefficient:

incen[(incen.device_name.str.contains(device_code[0]) == True)]|incen[(incen.device_name.str.contains(device_code[1]) == True)]|incen[(incen.device_name.str.contains(device_code[2]) == True)]|incen[(incen.device_name.str.contains(device_code[3]) == True)]
...and so on...

Let me understand how to use logical 'or' and for loop at the same time. Thanx.

Use lsit comprehension with np.logical_or.reduce , compare by True is not necessary:

L = [incen.device_name.str.contains(a, na=False) for a in device_code]
incen[np.logical_or.reduce(L)]

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