簡體   English   中英

如何使用python將數組的列存儲到不同的變量中?

[英]How to store columns of an array into different variables using 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
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM