Python 使用GroupBy创建条件列
我想根据数据框中某列的分组变量在数据框中创建一个新列,然后检查数据框中另一列的条件 我尝试使用np.where和pandas pd.groupby在数据框中创建一个状态列,在该数据框中,我根据对每个传感器ID的分组检查列中的下一个值是否大于当前值,并基于此,我尝试分配状态是否设置为重置,但是,我没有成功地使用代码Python 使用GroupBy创建条件列,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我想根据数据框中某列的分组变量在数据框中创建一个新列,然后检查数据框中另一列的条件 我尝试使用np.where和pandas pd.groupby在数据框中创建一个状态列,在该数据框中,我根据对每个传感器ID的分组检查列中的下一个值是否大于当前值,并基于此,我尝试分配状态是否设置为重置,但是,我没有成功地使用代码 import pandas as pd df = pd.DataFrame(data = {'Sensor_ID':['A1', 'A1', 'A1', 'A2','A2', 'A2'
import pandas as pd
df = pd.DataFrame(data = {'Sensor_ID':['A1', 'A1', 'A1', 'A2','A2', 'A2', 'A2', 'A3', 'A3', 'A3', 'A3', 'A3'], 'Reading':[81, 83.5, 87, 90, 81, 82, 85, 78, 79, 78, 80, 78]})
df
Sensor_ID Reading
0 A1 81.0
1 A1 83.5
2 A1 87.0
3 A2 90.0
4 A2 81.0
5 A2 82.0
6 A2 85.0
7 A3 78.0
8 A3 79.0
9 A3 78.0
10 A3 80.0
11 A3 78.0
我想使用np.where创建以下条件,但我想使用Sensor_ID作为分组变量
df['Status'] = np.where(df.Reading.shift(-1) > df.Reading, 'not_reset', 'reset')
我在groupby和transform中使用了np.where
df['Status'] = np.where(df.groupby('Sensor_ID')['Reading'].transform(df['Reading'].shift(-1) > df['Reading'], 'not_reset', 'reset'))
TypeError: 'Series' objects are mutable, thus they cannot be hashed
我还尝试将应用和转换与groupby一起使用,但出现错误:
df['Status'] = df.groupby('Sensor_ID').apply(lambda row: 'not_reset' if row['Reading'].shift(-1) > row['Reading'] else 'reset')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). --> As its comparing the whole series.
及
预期产出:
Sensor_ID Reading Status
0 A1 81.0 not_reset
1 A1 83.5 not_reset
2 A1 87.0 not_reset
3 A2 90.0 not_reset
4 A2 81.0 reset
5 A2 82.0 not_reset
6 A2 85.0 not_reset
7 A3 78.0 not_reset
8 A3 79.0 not_reset
9 A3 78.0 reset
10 A3 80.0 not_reset
11 A3 78.0 reset
您需要在分组IOW后应用条件,将
groupby
的结果与np.where
一起使用
我会使用groupby
和diff
,这与比较移位1的值相同。就这么简单,
np.where(
df.groupby('Sensor_ID')['Reading'].diff().fillna(1) > 0, 'not reset', 'reset')
array(['not reset', 'not reset', 'not reset', 'not reset', 'reset',
'not reset', 'not reset', 'not reset', 'not reset', 'reset',
'not reset', 'reset'], dtype='<U9')
np.where(
df.groupby('Sensor_ID')['Reading'].diff().fillna(1) > 0, 'not reset', 'reset')
array(['not reset', 'not reset', 'not reset', 'not reset', 'reset',
'not reset', 'not reset', 'not reset', 'not reset', 'reset',
'not reset', 'reset'], dtype='<U9')
df['Status'] = np.where(
df.groupby('Sensor_ID')['Reading'].diff().fillna(1) > 0, 'not reset', 'reset')
df
Sensor_ID Reading Status
0 A1 81.0 not reset
1 A1 83.5 not reset
2 A1 87.0 not reset
3 A2 90.0 not reset
4 A2 81.0 reset
5 A2 82.0 not reset
6 A2 85.0 not reset
7 A3 78.0 not reset
8 A3 79.0 not reset
9 A3 78.0 reset
10 A3 80.0 not reset
11 A3 78.0 reset