numpy数组和具有不同值的比较

时间:2019-03-02 21:18:15

标签: python-3.x csv numpy numpy-ndarray

出于可重复性的原因,我正在共享数据here

从第2列开始,我想读取当前行并将其与上一行的值进行比较。如果更大,我会继续比较。如果当前值小于上一行的值,我想将当前值(较小)除以上一个值(较大)。因此,以下代码:

import numpy as np
import matplotlib.pyplot as plt

protocols = {}

types = {"data_c": "data_c.csv", "data_r": "data_r.csv", "data_v": "data_v.csv"}

for protname, fname in types.items():
    col_time,col_window = np.loadtxt(fname,delimiter=',').T
    trailing_window = col_window[:-1] # "past" values at a given index
    leading_window  = col_window[1:]  # "current values at a given index
    decreasing_inds = np.where(leading_window < trailing_window)[0]
    quotient = leading_window[decreasing_inds]/trailing_window[decreasing_inds]
    quotient_times = col_time[decreasing_inds]

    protocols[protname] = {
        "col_time": col_time,
        "col_window": col_window,
        "quotient_times": quotient_times,
        "quotient": quotient,
    }

data_cnumpy.array,只有一个 unique quotient0.7data_r具有唯一的{ quotient的{​​1}}值。但是,0.5具有两个唯一的data_v值(quotient0.5)。

我想遍历这些CSV文件的0.8值,并使用简单的quotient语句对它们进行分类。我从numpy.array_equal那里获得了一个StackOverflow贡献者的帮助,如下所示。

if-else

这对于import numpy as np unique_quotient = np.unique(quotient) unique_data_c_quotient = np.r_[ 0.7] unique_data_r_quotient = np.r_[ 0.5] if np.array_equal( unique_quotient, unique_data_c_quotient ): print('data_c') elif np.array_equal( unique_quotient, unique_data_c_quotient ): print('data_r') data_c的值分别为0.7和0.5完全适用。这意味着它仅在data_r值是唯一的(或固定的)时有效。但是,当quotient值大于1时,它将不起作用。例如,quotient的商值在0.65和0.7之间(即data_m),而0.65<=quotient<=0.7的商值是两个data_v值(0.5和0.8)

我们如何使用quotient解决此问题?

1 个答案:

答案 0 :(得分:1)

如果您始终具有唯一的商,并且始终具有唯一的商界限,那么我将建议以下内容:

ud_m_bounds = np.r_[0.65,0.7]

uq = unique_quotient
uq_min,uq_max = uq.min(),uq.max()

def is_uq_bounded_by(unique_data_bounds):
  ud_min,ud_max = unique_data_bounds.min(), unique_data_bounds.max()
  left_bounded  = ud_min <= uq_min <= ud_max
  right_bounded = ud_min <= uq_max <= ud_max
  bounded = left_bounded & right_bounded
  return bounded

label = 'ERROR -- DATA UNCLASSIFIED'
if len(uq) > 2:
  if is_uq_bounded_by( unique_data_m_bounds ):
    label = 'data_m'
elif 0 < len(uq) <= 2:
  if np.array_equal( uq, unique_data_v_quotient):
    label = 'data_v' 
  if np.array_equal( uq, unique_data_c_quotient):
    label = 'data_c'
  elif np.array_equal( uq, unique_data_r_quotient):
    label = 'data_r'
print(label)

请注意,当数据开始重叠时,该方法将变得可疑。