簡體   English   中英

Python和excel讀取文件問題

[英]Python and excel reading files problem

如果這是一個愚蠢的問題,我很抱歉,但我已經為此工作了幾個小時,但我無法讓它發揮作用。 請幫忙!

我有一個源自 Excel 的 .txt 文件。 該文件包含字符串和數字,但我只對數字感興趣,這就是為什么我跳過第一行而只從第 2 列開始讀取。

   from numpy import *

我將它加載到 Python 中

    infile = open('europenewMatrix.txt','r')
    infile.readline() # skip the first line
    numbers = [line.split(',')[2:] for line in infile.readlines()]
    infile.close()

因為我需要對此進行計算,所以我將其轉換為矩陣:

    travelMat = array(numbers)

好的,但這並沒有將字符串轉換為整數,所以我手動做到了:

    for i in xrange(len(numbers)):
        for j in xrange(len(numbers)):
            travelMat[i,j] = int(self.travelMat[i,j])
        #end for

在這一點上,我希望我所有的條目都是整數,但如果我這樣做了

    print 'type is',type(self.travelMat[1,2]) 

答案是:

type is <type 'numpy.string_'>

我怎樣才能真正將所有條目轉換為整數? 多謝!

在創建數組之前,在讀取數字時轉換它們:

infile = open('europenewMatrix.txt','r')
infile.readline() # skip the first line
numbers = []
for line in infile:
    numbers.append([int(val) for val in line.split(',')[2:]])
infile.close()
travelMat = array(numbers)

如果您使用的是 csv 或類似 csv 的文件,請使用 csv 標准庫模塊。

from numpy import *
import csv

infile = open('europenewMatrix.txt', 'r')
reader = csv.reader(infile)
reader.next() # skip the first line
numbers = [[int(num) for num in row[2:]] for row in reader]
infile.close()

travelmat = array(numbers)

http://docs.python.org/library/csv.html

如果有人有一個可能具有相同標題但使用真正的 Excel (.xls) 文件的問題,試試這個(使用模塊xlrd ):

import xlrd
import numpy as np

sheet = xlrd.open_workbook('test_readxls.xls').sheet_by_name('sheet1')
n_rows, n_cols = 5,2
data = np.zeros((n_rows, n_cols))
for row in range(n_rows):
    for col in range(n_cols):
        data[row,col] = float(sheet.cell(row,col).value)

暫無
暫無

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

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