Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - iterating over column values and check for inside values

sorry, I am new to python. suppose, I have a data frame with column values repeating at some intervals

dest_num dest_voltage changes
322 45.1 stops responding
322 45.5 battery
322 46.7 low voltage
322 43.2 none
322 42.1 none
322 41.1 stops responding
322 45.1 battery
322 43.4 low voltage
322 43.2 none
322 42.1 critical voltage
322 40.1 dest_outage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to create a numeric id for each group, where the group starts on stops responding. You can do this by checking if changes equals stops responding and take the cumulative sum of the results.

Using this grouping you can check if all the values in your required list are in the changes column for that group and filter the results if they are.

You can of course drop the group column if it's no longer needed, but it seems like that might also be helpful after the fact.

import pandas as pd

df = pd.DataFrame({'dest_num': [322, 322, 322, 322, 322, 322, 322, 322, 322, 322, 322],
 'dest_voltage': [45.1,45.5,46.7,43.2,42.1,41.1,45.1,43.4,43.2,42.1,40.1],
 'changes': ['stops responding','battery','low voltage','none','none',
  'stops responding','battery','low voltage','none','critical voltage',
  'dest_outage']})

values = ['low voltage','critical voltage','dest_outage']
df['group'] = df['changes'].eq('stops responding').cumsum()
df.groupby('group').filter(lambda x: all([v in x['changes'].values for v in values]))

Output

   dest_num dest_voltage    changes            group
5   322     41.1            stops responding    2
6   322     45.1            battery             2
7   322     43.4            low voltage         2
8   322     43.2            none                2
9   322     42.1            critical voltage    2
10  322     40.1            dest_outage         2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...