使用 loadtxt 动态创建然后分配数组 (Python3)

Dynamically create then assign arrays with loadtxt (Python3)

描述

基本上我的问题是关于从 CSV 文件加载数据。我已经编写了一个代码,能够在数组中加载 given 列数(参见示例)。 现在我想改进代码,这样我就可以更改要读取和加载的列数,而无需每次都修改我的代码。换句话说,我希望我的代码能够动态适应我选择的列数。让我给你一个我现在的代码的例子。

代码示例

步骤 :

1。使用 Tkinter 我 select 我想要加载的文件,这部分代码 returns file_path,包含几个文件路径。

2 然后我定义了CSV读取有用的参数。我创建了要加载数据的数组,然后加载数据。

n = len(file_path)    # number of files

# here I just determine the size of each files with a custom function, m is the maximum size
all_size , m = size_data(file_path,row_skip,col_to_read,delim)

# I create the arrays
shape = (n, m)
time = zeros(shape)
CH1 = zeros(shape)

# define CSV parameters before using loadtxt
row_skip = 5
delim = ';'
col_to_read = (0,1)    # <= This is where I choose the columns to be read

# I load the arrays
for k in range(0, len(file_path)):
    end = all_size[k]    # this is the size of the array to be loaded.
                         # I do this in order to avoid the annoying error
                         # ValueError: could not broadcast input array from shape (20) into shape (50)

    time[k][:end], CH1[k][:end] = loadtxt(file_path[k],
                                           delimiter=delim,
                                           skiprows=row_skip,
                                           usecols=col_to_read,
                                           unpack=True)

我的问题是,如果每个文件有 3 列,即 col_to_read = (0,1,2),我必须在创建和加载期间添加一个新数组 CH2 = zeros(shape)。我想要一个动态适应我想要加载的列数的解决方案。只有 col_to_read 会被手工更改。 理想情况下我想在一个函数中实现这段代码,因为我做了很多数据分析,我不希望每个程序都粘贴相同的代码。

第一个想法

我已经找到了一种动态创建给定数量的零数组的方法 ()。很直接。

dicty = {}
for i in file_path:
    dicty[i] = []

这看起来不错,但现在我想让最后一行工作,无论变量的数量是多少。我相信有一种方便的方法来调整我的代码并使用它 dicty,但有些东西我不明白,我被卡住了。

如有任何帮助,我将不胜感激。

好吧,几周以来我一直在想这个问题,我找到了解决方案。在这里问肯定有助于我更清楚地解决问题。

我了解了更多有关词典的知识,因为它对我来说是新事物,而且我知道它非常强大。我可以用几行替换整个代码:

def import_data(file_path,row_skip,col_to_read,delim):

# file_path is all the PATH strings of CSV files
# row_skip just to start loading from certain row
# col_to_read = (0,1,2), where I choose the col to read
# delim = ';' the delimiter for my CSV files

    dicty = {}                       # create ditcionary
    for i in file_path:              # in order to associate each file
        dicty[i] = []                # with n columns

    for k in range(0, len(file_path)):
        dicty[file_path[k]] = loadtxt(file_path[k], delimiter=delim,
                                      skiprows=row_skip, usecols=col_to_read,
                                      unpack=True)

    # it gives
    # dicty = {'my_file1.csv': array([1,2,3]),
    #          'my_file2.csv': array([2,4,6]),
    #          'my_file3.csv': array([5,10,15])}

    return dicty

这很简单。字典的第一个条目将填充所有列,依此类推,我不需要告诉字典我将给它多少 col。然后读取数据我使用 dicty.get(file_path[0]) 例如。这可能不是最优的,但我肯定可以使用 for 循环创建变量以摆脱 dicty.get() 方法。

告诉我您对此有何看法,尤其是计算时间。有时我有 20 个文件,其中包含 200 000 行 3 列。也许我可以优化加载。