python - 如何使用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])
解决方案
如果您有一个行列表,并且想要获取列列表,则可以使用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
]
推荐阅读
- javascript - 了解 jQuery 函数的调用/对初学者的小型响应式布局脚本的反馈
- amazon-web-services - 我可以在 AWS Autoscale 组终止运行不正常的实例之前对其进行快照吗?
- python - 带有 Scikit-Learn 的 Google Cloud ML 引发:“dict”对象没有“lower”属性
- php - php嵌套函数p
- asp.net-core-2.0 - 模型验证.Net Core 2.0 Web Api 不工作
- python - 如何在 python 中创建一个不会创建重复数字的随机数生成器
- php - MethodNotAllowedException Laravel API
- php - 我可以在同一函数中获取之前上传的文件的表 ID 吗?
- idris - 完整证明如果最后一个列表元素不在列表中,则前置不会如此
- c++ - 联合初始化中的结构