2017-04-17 42 views
1

所以我有這個程序。它記錄來自加速度計的數據。這是數據的格式。它保存在.csv文件中。在我的for循環.split()只能工作一次

time, x, y, z 
0.000000,0.064553,-0.046095,0.353776 

下面是在我的程序頂部聲明的變量。

length = sum(1 for line in open('couchDrop.csv')) 
wholeList = [length] 
timeList = [length]#holds a list of all the times 
xList = [length] 
yList = [length] 
zList = [length] 

我想創建四個列表;時間,x,y,z。目前整個數據文件存儲在一個列表中。列表中的每行包含4個數字,分別代表時間,x,y和z。我需要將wholeList分成四個不同的列表。這裏就是發生這種情況的子程序:

def easySplit(): 
    print "easySplit is go " 
    for i in range (0, length): 
     current = wholeList[i] 
     current = current[:-2] #gets rid of a symbol that may be messing tings up 
     print current 
     print i 
     timeList[i], xList[i], yList[i], zList[i] = current.split(',') 
     print timeList[i] 
     print xList[i] 
     print yList[i] 
     print zList[i] 
     print "" 

這是我得到的錯誤:

Traceback (most recent call last): 
    File "/home/william/Desktop/acceleration plotter/main.py", line 105, in   <module> 
    main() 
    File "/home/william/Desktop/acceleration plotter/main.py", line 28, in main 
easySplit() 
    File "/home/william/Desktop/acceleration plotter/main.py", line 86, in easySplit 
timeList[i], xList[i], yList[i], zList[i] = current.split(',') 
IndexError: list assignment index out of range` 

另一個奇怪的是,我點分似乎通過循環精細工作的第一次。

任何幫助將不勝感激。

回答

0

對於像這樣的數據操作,我建議使用Pandas。在一行中,您可以將數據從CSV讀取到數據框中。

import pandas as pd 
df = pd.read_csv("couchDrop.csv") 

然後,您可以輕鬆地按名稱選擇每個列。您可以將數據操縱爲pd.Series或操作爲np.array或轉換爲列表。例如:

x_list = list(df.x) 

您可以在http://pandas.pydata.org/pandas-docs/stable/10min.html找到更多關於熊貓的信息。

編輯:與您的原始代碼的錯誤是像xList = [length]語法不會創建一個長度列表length。它創建一個長度爲1的列表,其中包含一個值爲length的int元素。

0

代碼行wholeList = [length]不創建長度列表= length。它只創建一個列表,只有一個元素是整數length,所以如果你是print(wholeList),你將只能看到[3] 由於列表在python中是可變的,所以你可以直接給wholeList = []並且不斷追加元素。它不必具有特定的長度。

當你這樣做current.split(',')這是從wholeList派生,它試圖即[3]

0

所有你需要的是變化這一

length = sum(1 for line in open('couchDrop.csv')) 
wholeList = [0]*length 
timeList = [0]*length#holds a list of all the times 
xList = [0]*length 
yList = [0]*length 
zList = [0]*length 

,但應該使用追加拆分唯一的數據可用於第一次迭代。