【发布时间】:2019-07-21 06:34:58
【问题描述】:
我正在使用三个小型数据集,出于可重复性的原因,我正在共享数据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_c 是一个numpy.array,它只有一个唯一 quotient 值0.7,data_r 也是一个唯一quotient 值0.5。但是,data_v 有两个唯一的 quotient 值(0.5 或 0.8)。
我想遍历这些 CSV 文件的 quotient 值并使用简单的 if-else 语句(例如,if quotient==0.7: print("data_c"))对它们进行分类,但我收到此错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
更新:我发现这个错误可以通过使用.all()函数来解决,如下所示。
if (quotient==0.7).all():
print("data_c")
elif (quotient>=0.5).all() and (quotient <=0.8).all():
print("data_v")
elif (quotient==0.5).all():
print("data_r")
但是,这会打印出data_c, data_v, data_v。我们该如何解决这个问题?
【问题讨论】:
-
如何比较第一个元素?你考虑过用熊猫吗?
-
不,我没有使用
pandas。 -
你想看一个例子还是反对?
-
不,我不反对它,只要它计算我在问题中包含的所有文件的
quotient,这就是我坚持使用numpy的原因之一。 -
你是否跳过了第一个值?