我有一个具有电压和电流值的熊猫多索引数据文件:
Dataframe:
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我希望转换dataframe,以便为每个键获得一个布尔值:
对于某些任意给定的电压和电流,例如60V和10A,我检查数据中最接近的电压值,然后检查相应的电流是大于还是小于给定的电流。举个例子来说,最终应该是这样的:
a b 'name'
1 1 absd 0
2 quat 1有了一些for循环,我就可以运行它,但是是否有一种很好的、高效的方法来处理熊猫,避免循环和其他迭代方法呢?
发布于 2019-07-08 16:55:16
下面是我使用groupby和idxmin的方法
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发布于 2019-07-08 17:00:27
您可以使用pd.IndexSlice分别选择数据的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: int32https://stackoverflow.com/questions/56938987
复制相似问题