Skip to main content
 首页 » 编程设计

python之遍历多个 CSV 文件

2024年11月24日14落叶

我正在处理三个小型数据集,出于可重复性的原因,我共享数据 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只有一个unique quotient值 0.7 , 和 data_r 一样具有独特的 quotient 0.5 的值.然而,data_v有两个独特的quotient值(0.5 或 0.8 )。

我想遍历 quotient这些 CSV 文件的值并使用简单的 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 .我们如何解决这个问题?

请您参考如下方法:

如果我没理解错的话,您是在要求使用 quotient 数组的unique 值对数据进行分类。如果是这种情况,那么您可以轻松利用 numpy.unique。帮助:

import numpy as np 
unique_quotient = np.unique(quotient) 
# For data_c this is just a single value 

如果您将 unique_quotient 数组放在您的 protocol_dictionary 中,那么它会给您一些可以比较的东西(例如 using numpy.array_equal):

unique_data_c_quotient = np.r_[ 0.7 ] 
if np.array_equal( unique_quotient, unique_data_c_quotient ):  
    print('data_c') 
...