使用python获取32x32矩阵将这些矩阵中的许多附加到单个数组中,然后向每个矩阵添加时间戳索引

2024-04-30 06:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编写python代码非常陌生,我正在使用一个.CSV文件,该文件在1024列的行中给出一个32x32的矩阵,并带有时间戳。我重新调整了数据的形状,得到32x32个数组,并循环遍历每一行,将矩阵附加到一个numpy数组中。你知道吗

`i = 0 
while i < len(df_array):
    if i == 0:
    spec = np.reshape(df_array[i][np.arange(1,1025)], (32,32))
    spectrum_matrix = spec
else: 
    spec = np.reshape(df_array[i][np.arange(1,1025)], (32,32))
    spectrum_matrix = np.concatenate((spectrum_matrix, spec), axis = 0)
i = i + 1
print("job done")`

我想做的是从原始数据文件中添加时间戳,并将它们添加到每个矩阵中,从而允许我在5分钟的平均时间内重新采样数据。我还想绘制一个类似于Drop size distribution的图

作为参考,我阅读了data.CSV中的pandas,这里是一个原始数据部分的示例:01.06.2017;18:22:20;0.122;0.00;51;7.401;10375;18745;57;27;0.00;23.6;0.110;0; &光谱

光谱后面的是32x32矩阵。你知道吗

提前感谢您的帮助!你知道吗


Tags: 文件csv数据df原始数据np时间矩阵
1条回答
网友
1楼 · 发布于 2024-04-30 06:15:45

Python和相关的包可以在没有循环的情况下做很多事情

根据我对你们数据的理解,你们有一个(8640 x 32 x 32)的数据结构(时间x大小x速度)。 Pandas可以很好地处理2D数据结构,但是对于高维数据,我建议您熟悉xarray。使用这个包和pandas,您可以创建和操作数据,而不必求助于循环。你知道吗

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xarray as xr
import seaborn as sns
%matplotlib inline

#create random data
data = (np.random.binomial(n =5, p  =0.2, size =(8640,32,32))*1000).astype(int)

#create labels for data
sizes= np.linspace(1,5,32)
velocities = np.linspace(1,1000, num = 32)

#make time range of 24 hours with 10sec intervals
ind = pd.date_range(start='2014-01-01', periods=8640, freq='10s') 

#convert data to xarray 3D data structure
df = xr.DataArray(data, coords = [ind, sizes, velocities], 
                  dims = ['time', 'size', 'speed'])

#make a 5 min average of the data
min_average= df.resample('300s', dim = 'time', how = 'mean')

#plot sample of data and 5 min average
my1d = min_average.isel(size = 5, speed= 10)
my1d.plot(label = '5 min avg')
plt.gca()
df.isel(size = 5, speed =10).plot(alpha = 0.3, c = 'r', label = 'raw_data')
plt.legend() 

example plot of your data


至于制作一个像你这样的分布图,把事情联系起来会变得有点棘手,但这是可能的:

#transform your data to only have mean speed for each time and size
#and convert to pandas dataframe
mean_speed =min_average.mean(dim = ['speed'])
#for some reason xarray make you name the new column when you convert
#to a pandas dataframe. I then get rid of the extra empty variable with 
#a list comprehension
df= mean_speed.to_dataframe('').unstack().T
df.index =  np.array([np.array(i)[1].astype(float) for i in df.index])

#make a contourplot of your new data
plt.contourf(df.columns, df.index, df.values, cmap ='PuBu_r')
plt.title('mean speed')
plt.ylabel('size')
plt.xlabel('time')
plt.colorbar()

enter image description here

相关问题 更多 >