[英]Importing data and variable names from a text file in Python
我有一個包含模擬數據的文本文件(60列,100k行):
a b c
1 11 111
2 22 222
3 33 333
4 44 444
...第一行中的變量名稱,下面(列中)是相應的數據(浮點類型)。
我需要將所有這些變量與他們在Python中的數據一起用於進一步的計算。 例如,當我插入時:
print(b)
我需要從第二列接收值。
我知道如何導入數據:
data=np.genfromtxt("1.txt", unpack=True, skiprows = 1)
“手動”分配變量:
a,b,c=np.genfromtxt("1.txt", unpack=True, skiprows = 1)
但是我在獲取變量名時遇到了麻煩:
reader = csv.reader(open("1.txt", "rt"))
for row in reader:
list.append(row)
variables=(list[0])
如何更改此代碼以從第一行獲取所有變量名稱並將它們分配給導入的數組?
答案是: 你不想這樣做 。
字典就是為了這個目的而設計的:你真正想要的數據結構是這樣的:
data = {
"a": [1, 2, 3, 4],
"b": [11, 22, 33, 44],
"c": [111, 222, 333, 444],
}
...然后您可以使用例如data["a"]
輕松訪問。
它可以做你想要的,但通常的方式是一個hack,它依賴於Python在內部使用(鼓勵)一個dict
存儲變量的事實 - 並且由於你的代碼不知道這些變量的名稱,你將會使用字典訪問來阻止它們...所以你可能只是首先使用字典。
值得指出的是,這在Python中是刻意變得困難的,因為如果你的代碼不知道變量的名稱,那么它們是定義數據而不是邏輯,應該這樣對待。
如果您還不相信,這里有一篇關於這個主題的好文章:
您可以考慮使用關聯數組 (在Python中稱為dict
)來存儲變量及其值,而不是嘗試分配名稱。 然后代碼看起來像這樣(從csv
docs中大量借用):
import csv
with open('1.txt', 'rt') as f:
reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
lineData = list()
cols = next(reader)
print(cols)
for col in cols:
# Create a list in lineData for each column of data.
lineData.append(list())
for line in reader:
for i in xrange(0, len(lineData)):
# Copy the data from the line into the correct columns.
lineData[i].append(line[i])
data = dict()
for i in xrange(0, len(cols)):
# Create each key in the dict with the data in its column.
data[cols[i]] = lineData[i]
print(data)
然后, data
包含您的每個變量,可以通過data['varname']
。
因此,例如,您可以根據問題中提供的輸入執行data['a']
以獲取列表['1', '2', '3', '4']
。
我認為,與上面顯示的基於dict的方法相比,嘗試基於文檔中的數據創建名稱可能是一種相當尷尬的方式。 但是,如果你真的想這樣做,你可能會考慮使用Python中的反思 (這個主題我真的不知道)。
感謝@ andyg0808和@Zero Piraeus,我找到了另一個解決方案。 對我來說,最合適的 - 使用熊貓數據分析庫。
import pandas as pd
data=pd.read_csv("1.txt",
delim_whitespace=True,
skipinitialspace=True)
result=data["a"]*data["b"]*3
print(result)
0 33
1 132
2 297
3 528
...其中0,1,2,3是行索引。
這是將變量名和數據的.txt文件轉換為NumPy數組的簡單方法。
D = np.genfromtxt('1.txt',dtype='str') # load the data in as strings
D_data = np.asarray(D[1::,:],dtype=float) # convert the data to floats
D_names = D[0,:] # save a list of the variable names
for i in range(len(D_names)):
key = D_names[i] # define the key for this variable
val = D_data[:,i] # set the value for this variable
exec(key + '=val') # build the variable code here
我喜歡這種方法,因為它易於遵循並且易於維護。 我們可以按如下方式壓縮此代碼:
D = np.genfromtxt('1.txt',dtype='str') # load the data in as strings
for i in range(D.shape[1]):
val = np.asarray(D[1::,i],dtype=float) # set the value for this variable
exec(D[0,i] + '=val') # build the variable
兩個代碼都做同樣的事情,返回名為a,b和c的NumPy數組及其關聯數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.