如果数据低于datafram中的treshold,则获取布尔值

2024-09-27 09:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有电压和电流值的多索引数据帧:

数据帧:

a b 'name' unit
             0    1    2    3   ... 
1 1  absd A  0  1.1  3.6  7.6
          V  6   66  103  202
  2  quat A  1  2.5 14.9  nan
          V  0    3   66  nan

我想转换数据帧,以便为每个键获得一个布尔值:

对于任意给定的电压和电流,比如60V和10A,我检查数据帧中最近的电压值,然后检查相应的电流是否大于或小于给定的值。 例如,最后应该是这样的:

a b 'name'
1 1  absd  0          
  2  quat  1

有了一些for循环,我就可以运行了,但是有没有一个好的、有效的方法来使用pandas,避免for循环和其他迭代方法呢?你知道吗


Tags: 数据方法namepandasforunitnan电流
2条回答

可以使用^{}分别选择数据帧的V和A,然后创建布尔掩码,查看A的值是否大于10,V的值是否最接近60。你知道吗

amp_min = 10
volt_value = 60

# mask for A
mask_A = (df.loc[pd.IndexSlice[:,:,:, 'A'], :] > amp_min).reset_index(level=-1, drop=True)

#mask for V by finding the column position of the minimum difference
mask_V = pd.get_dummies((df.loc[pd.IndexSlice[:,:,:, 'V'], :] - volt_value)
                           .abs().idxmin(axis=1)).reset_index(level=-1, drop=True)

#combine both mask and use any per row
print ((mask_A & mask_V).any(1).astype(int))
a  b  name
1  1  absd    0
   2  quat    1
dtype: int32

我的方法是groupbyidxmin

df = df.stack().unstack('unit')

# function for each v and a
def get_thresh(df, v, a):
    v_diff = (df['V'] - v).abs()
    idx = v_diff.groupby(['a','b','name']).idxmin()

    return (df.loc[idx,'A']
              .gt(a).astype(int)
              .reset_index(level=-1, drop=True)
           )

get_thresh(df, 60,10)

退货:

a  b  name   
1  1  absd    0
   2  quat    1
Name: A, dtype: int32

相关问题 更多 >

    热门问题