Skip to main content
 首页 » 编程设计

python之如何使用给定值比较数据框列

2024年12月31日7cyq1162

我有一个如下所示的数据框:

>>> df = pd.DataFrame( {'InLevel_03': [12, 12, 13, 12, 11,], 'InLevel_02': [11.5, 11.5, 12.5, 11.5, 10.5], 'InLevel_01': [11, 10.5, 12, 10.5, 9], 'OutLevel_01': [10.5, 10, 11.5, 10, 8.5], 'OutLevel_02': [10, 9.5, 11, 9.5, 8], 'OutLevel_03': [9.5, 9, 10, 9, 7.5]} ) 
 
>>> df 
   InLevel_03  InLevel_02  InLevel_01  OutLevel_01  OutLevel_02  OutLevel_03 
0          12        11.5        11.0         10.5         10.0          9.5 
1          12        11.5        10.5         10.0          9.5          9.0 
2          13        12.5        12.0         11.5         11.0         10.0 
3          12        11.5        10.5         10.0          9.5          9.0 
4          11        10.5         9.0          8.5          8.0          7.5 

如果给定值是 0.5,我想检查连续是否有大于给定值的间隙。例如,在第2行中,InLevel_02(11.5)和InLevel_01(10.5)之间的差距是11。在第5行中,InLevel_02(10.5)和InLevel_01(9.0)之间的差距是10和9.5。

此作业的结果如下所示:

 gapLevel    count    # row number, column name of each gap 
       11        2    # (1, InLevel_02 - 1, InLevel_01), (3, InLevel_02 - 3, InLevel_01) 
     10.5        1    # (2, OutLevel_02 - 2, OutLevel_03) 
       10        1    # (4, InLevel_02 - 4, InLevel_01) 
      9.5        1    # (4, InLevel_02 - 4, InLevel_01) 

我尝试将数据帧转换为数组(使用 .to_records)并使用循环将每个值与其下一个值进行比较,但是当两个值之间有超过 1 个级别时代码变得太复杂,我想知道如果有更有效的方法来做到这一点。

请您参考如下方法:

这是一种方法:

您可以首先获取行和列的索引列表,从中提取计数,检查 df 减去自身的移位版本(参见 pd.shift )是否大于 0.5:

t = 0.5 
# df = df.astype(float) # if it isn't already 
rows, cols = np.where(df - df.shift(-1, axis = 1) > t) 
# (array([1, 2, 3, 4]), array([1, 4, 1, 1])) 

使用列表推导式从这些行和列中的值中获取排列(请注意,此方法假定值在整个列中不断减少):

v = [np.arange(*df.iloc[r,[c+1, c]].values, step=t)[1:] for r, c in zip(rows, cols)] 
# [array([11.]), array([10.5]), array([11.]), array([ 9.5, 10. ])] 

使用 Counter 从计数中创建一个新的 Series:

from itertools import chain 
from collections import Counter 
 
x = list(chain.from_iterable(v.values)) 
#[11.0, 10.5, 11.0, 9.5, 10.0] 
pd.Series(Counter(x), name = 'count') 
 
11.0    2 
10.5    1 
9.5     1 
10.0    1 
Name: count, dtype: int64