Python筆記(讀取txt文件中的數據)


在機器學習中,常常需要讀取txt文本中的數據,這里主要整理了兩種讀取數據的方式

數據內容

  • 共有四列數據,前三列為特征值,最后一列為數據標簽
40920	8.326976	0.953952	3
14488	7.153469	1.673904	2
26052	1.441871	0.805124	1
75136	13.147394	0.428964	1
38344	1.669788	0.134296	1
72993	10.141740	1.032955	1
35948	6.830792	1.213192	3
42666	13.276369	0.543880	3
67497	8.631577	0.749278	1
35483	12.273169	1.508053	3

方式一:手動讀取

from numpy import *
import operator
from os import listdir

def file2matrix(filename):
    fr = open(filename)
    numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = zeros((numberOfLines,3))        #prepare matrix to return
    classLabelVector = []                       #prepare labels return   
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector

dataMat,dataLabel = file2matrix("datingTestSet2.txt")

print(dataMat, dataLabel)

方式二:使用pandas

import numpy as np
import pandas as pd
df_news = pd.read_table('datingTestSet2.txt',header = None)
df_news

詳細可以查看下面文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM