2016-08-26 63 views
0

我有一個CVS文件,其中有數字的三列高達每三個數字:閱讀文件作爲陣列

1 0 0 
2 0 0 
3 0 0 
4 0 0 
5 0 0 
6 0 0 
7 0 0 
8 0 0 
9 0 0 
10 0 0 
11 0 0 

我想分別讀取列,並能夠利用它們作爲使用數組:

data = np.loadtxt('file.csv') 
x = data[:, 0] 
y = data[:, 1] 

但我發現了:

X = np.array(X, dtype) 
ValueError: setting an array element with a sequence. 

相反,如果我使用的線路x,y = np.loadtxt('Beamprofile.txt', usecols=(0,1), unpack=True)錯誤消失,但xy在進一步的操作中似乎沒有被正確讀取。

+2

可能的重複[從python讀取csv文件](http://stackoverflow.com/questions/14725020/read-csv-file-from-python) – gsamaras

+0

這是一個numpy特定的文件讀取isue​​。 – hpaulj

+0

顯示'data'的形狀和dtype。甚至可以打印幾行數據或文件。 – hpaulj

回答

0

與樣品:

In [1]: data=np.loadtxt('stack39174768.txt') 
In [2]: data 
Out[2]: 
array([[ 1., 0., 0.], 
     [ 2., 0., 0.], 
     [ 3., 0., 0.], 
     [ 4., 0., 0.], 
     [ 5., 0., 0.], 
     [ 6., 0., 0.], 
     [ 7., 0., 0.], 
     [ 8., 0., 0.], 
     [ 9., 0., 0.], 
     [ 10., 0., 0.], 
     [ 11., 0., 0.]]) 
In [3]: x=data[:,0] 
In [4]: y=data[:,1] 
In [5]: x 
Out[5]: array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.]) 
In [6]: y 
Out[6]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) 

在哪裏的問題?是否有關於剪輯中沒有看到的文件?

In [8]: x,y = np.loadtxt('stack39174768.txt', usecols=(0,1), unpack=True) 

產生相同xy

我問起形狀和D型

In [11]: data.shape 
Out[11]: (11, 3) 
In [12]: data.dtype 
Out[12]: dtype('float64') 

我喜歡np.genfromtxt好一點,但在這種情況下,它會產生相同的data

0

最簡單的解決方案可能是在python中使用pandas模塊,它可以自由將列值作爲numpy數組使用,您可以輕鬆地將其轉換爲列表。

import pandas as pd 

    df = pd.read_csv(open("name_of_the_csv.csv")) 
    # For one column, lets say the 1st one 
    column_1_list = df[df.columns[0]].values 

如果你想訪問你可以使用環列,並做到這一點如下圖所示:

df = pd.read_csv(open("name_of_the_csv.csv")) 
    for i in xrange(len(df.columns)): 
     column_list = df[df.columns[i]].values 
+0

對於像'numpy'這樣的文件來說,它只是一個有能力的,簡單的'pandas'。 – hpaulj