首页 > 解决方案 > 如何使用python将数组的列存储到不同的变量中?

问题描述

我是 python 新手。我正在尝试将数组的列存储到不同的变量中。我拥有的数组大小为 40x100,我想将这 100 列存储到 100 个变量中。然后我将用它来绘制和拟合它们。

我尝试使用以下代码,但它将所有列存储在一个变量中

import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('PE1889_0__old.txt', skip_header=9) #imports data from file and stores in data
sp= data[:4000,0]
Y = data[:4000,5]
plt.plot(sp,Y)
plt.xlabel("Scan path [mm]")
plt.ylabel("Y [mm]")
X=np.reshape(sp,(40,100)) #reshapes sp into a 40x100 matrix
print(len(X[0,:]))
X_col = (len(X[:,0]))
d={}
for i in range(X_col):
  d["col{0}".format(i)]=(X[:,i])

标签: python

解决方案


如果您有一个行列表,并且想要获取列列表,则可以使用zip内置函数

rows = [ # list of 40 rows, each with 100 values
    [1, 2, 4, 5, 6 ,7, ...., 100],
    [1, 2, 4, 5, 6 ,7, ...., 100],
    [1, 2, 4, 5, 6 ,7, ...., 100],
    .
    .
    .
    [1, 2, 4, 5, 6 ,7, ...., 100],  # 40th row in this list, containing 100 values
]

columns = list(zip(*data))

print(columns)

输出

[ # list of 100 columns, each with 40 values
   [0, 0, 0, 0, 0, 0, 0, ..., 0],
   [1, 1, 1, 1, 1, 1, 1, ..., 1],
   .
   .
   .,
   [100, 100, 100, 100, 100, 100, 100, ..., 100], # 100th column, containing 40 values
]

推荐阅读