2017-04-19 461 views
0

我對Python很新,遇到了一個小問題,但(看起來很難)。在Python中從一個txt文件中提取數字的行/列

我有一個包含以下內容的txt文件:

-2  2.1  -0.365635756 
0  2.4  0.347433737 
2  2.5  0.263774619 
4  3.5  -0.244930974 
6  4.2  -0.004564913 

我的目標就是以某種方式從Python中的文件中提取不同的行/列的列表或數組(再次使用,我是相當新對此)。例如,我如何使用第一列中的數據製作列表[-2,0,2,4,6]?

目前,我有我的工作下面的代碼:

import numpy as np 

with open('Numbers.txt', 'r') as f: 
    fcontents = f.read() 
    print(fcontents) 

x = np.array(fcontents) 

這樣做的目的是編寫使用數組來計算我們的項目說明給予不同變量的程序。

非常感謝您的任何幫助,

盧克。

+0

使用空格字符作爲分隔符的文本文件中的每一行 –

+0

的可能的複製[如何的文本文件轉換成一個Python列表](HTTP:/ /stackoverflow.com/questions/8205807/how-to-convert-a-text-file-into-a-list-in-python) – Barney

回答

0

我沒有用numpy的,但如果你想分成列,你可以做這樣的事情

col1 = [] 
col2 = [] 
col3 = [] 

with open('Numbers.txt', 'r') as f: 
    for line in f: 
     first, second, third = line.split() 
     col1.append(first) 
     col2.append(second) 
     col3.append(third) 

print(col1) 
print(col2) 
print(col3) 

其輸出

['-2', '0', '2', '4', '6'] 
['2.1', '2.4', '2.5', '3.5', '4.2'] 
['-0.365635756', '0.347433737', '0.263774619', '-0.244930974', '-0.004564913'] 
+0

這是完美的,謝謝你! –

1

這可能是pandas工作:

import pandas as pd 

df = pd.read_fwf('Numbers.txt', header=None) 
first_col = df[0] 

assert first_col.mean() == 2 
assert first_col.median() == 2 
assert sum(first_col) == 10 

參考文獻:

+0

耶!熊貓規則!但對於這種特殊的文件格式,我會使用[pd.read_fwf()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html) – MaxU

+1

@MaxU - 同意。謝謝! –

0

你可以導入你的數據作爲numpy.array

import numpy as np 

data = np.genfromtxt('Numbers.txt', unpack=True).T 

隨後,檢索列/行是作爲索引一樣簡單/切片一個numpy.array

print(data[1,:]) 
print(data[:,1]) 

這將導致

[ 0.   2.4   0.34743374] 
[ 2.1 2.4 2.5 3.5 4.2] 
相關問題