txt 文件的几十行处理到只需要用pd.read

mac2025-10-14  8

import pandas as pd from urllib.request import urlretrieve import numpy as np #获取数据 ##EURO STOXX 50 es_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt' urlretrieve(es_url, './data/es.txt') #数据清洗 ''' * 两个额外的标题行无需导入 * 从2001-12-27(即27.12.2001)开始,数据集的最后一行后面突然增加了一个额外的分号 ''' #读取整个数据集并删除所有空白 lines = open('./data/es.txt', 'r').readlines() lines = [line.replace(' ','') for line in lines] print(lines[:6]) for line in lines[3883:3890]: print(line[41:])

输出:

['PriceIndices-EUROCurrency\n', 'Date;Blue-Chip;Blue-Chip;Broad;Broad;ExUK;ExEuroZone;Blue-Chip;Broad\n', ';Europe;Euro-Zone;Europe;Euro-Zone;;;Nordic;Nordic\n', ';SX5P;SX5E;SXXP;SXXE;SXXF;SXXA;DK5F;DKXF\n', '31.12.1986;775.00;900.82;82.76;98.58;98.06;69.06;645.26;65.56\n', '01.01.1987;775.00;900.82;82.76;98.58;98.06;69.06;645.26;65.56\n'] 317.10;267.23;5268.36;363.19 322.55;272.18;5360.52;370.94 322.69;272.95;5360.52;370.94 327.57;277.68;5479.59;378.69; 329.94;278.87;5585.35;386.99; 326.77;272.38;5522.25;380.09; 332.62;277.08;5722.57;396.12;

从输出结果可以看出,

数据集的空白行已成功删除,从2001-12-27起,每个数据行最后多出了一个额外的分号

为了使数据集更容易导入,需进行如下处理:

1.生成一个新的文本文件2.删除不需要的标题行3.在新文件中写入对应的新标题行4.添加一个辅助列DEL(捕捉最后的分号)把所有数据行写入新文件 new_file = open('./data/es50.txt', 'w') new_file.writelines('date' + lines[3][:-1] + ';DEL' + lines[3][-1]) # DEL用来占位 new_file.writelines(lines[4:]) new_file.close()

查看新文件前几行(包括标题):

new_lines = open('F:/python/data/es50.txt', 'r').readlines() new_lines[:5] ['date;SX5P;SX5E;SXXP;SXXE;SXXF;SXXA;DK5F;DKXF;DEL\n', '31.12.1986;775.00;900.82;82.76;98.58;98.06;69.06;645.26;65.56\n', '01.01.1987;775.00;900.82;82.76;98.58;98.06;69.06;645.26;65.56\n', '02.01.1987;770.89;891.78;82.57;97.80;97.43;69.37;647.62;65.81\n', '05.01.1987;771.89;898.33;82.82;98.60;98.19;69.16;649.94;65.82\n']

再用pandas的read_csv函数导入:

es = pd.read_csv('F:/python/data/es50.txt', index_col=0, parse_dates=True,sep=';',dayfirst=1) np.round(es.tail()) SX5P SX5E SXXP SXXE SXXF SXXA DK5F DKXF DEL date 2016-09-28 2847.0 2991.0 343.0 324.0 408.0 350.0 9072.0 581.0 NaN 2016-09-29 2849.0 2992.0 343.0 324.0 408.0 351.0 9112.0 583.0 NaN 2016-09-30 2843.0 3002.0 343.0 325.0 408.0 350.0 9116.0 583.0 NaN 2016-10-03 2845.0 2998.0 343.0 325.0 408.0 351.0 9131.0 584.0 NaN 2016-10-04 2871.0 3030.0 346.0 328.0 411.0 354.0 9212.0 589.0 NaN

辅助列已经完成使命,可删除:

del es['DEL'] print(np.round(es.tail()))

输出:

SX5P SX5E SXXP SXXE SXXF SXXA DK5F DKXF date 1986-12-31 775.0 901.0 83.0 99.0 98.0 69.0 645.0 66.0 1987-01-01 775.0 901.0 83.0 99.0 98.0 69.0 645.0 66.0 1987-01-02 771.0 892.0 83.0 98.0 97.0 69.0 648.0 66.0 1987-01-05 772.0 898.0 83.0 99.0 98.0 69.0 650.0 66.0 1987-01-06 776.0 902.0 83.0 99.0 99.0 70.0 652.0 66.0

注:关于np.around()函数,可点击【NumPy】 之常见运算np.around、np.floor、np.ceil、np.where)了解

上述的代码已将该数据集清洗完成

说个重要的事情,上面关于EURO STOXX 50的所有代码,等价于下面的几行代码!!!:

import pandas as pd es_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt' cols = ['SX5P', 'SX5E', 'SXXP', 'SXXE', 'SXXF', 'SXXA', 'DK5F', 'DKXF'] es = pd.read_csv(es_url, index_col=0, parse_dates=True, sep=';', dayfirst=True, header=None, skiprows=4, names=cols) es.tail() Out[55]: SX5P SX5E SXXP ... SXXA DK5F DKXF 2016-09-28 2846.55 2991.11 342.57 ... 350.45 9072.09 581.27 2016-09-29 2848.93 2991.58 342.72 ... 350.90 9112.09 582.60 2016-09-30 2843.17 3002.24 342.92 ... 350.09 9115.81 583.26 2016-10-03 2845.43 2998.50 343.23 ... 350.92 9131.24 584.32 2016-10-04 2871.06 3029.50 346.10 ... 353.92 9212.05 588.71 [5 rows x 8 columns]

关于pd.read_csv(es_url, index_col=0, parse_dates=True, sep=’;’, dayfirst=True, header=None, skiprows=4, names=cols)的参数

filepath_or_buffer:可以是URL,可用URL类型包括:http, ftp, s3和文件;也可以是本地文件index_col : int or sequence or False, default None 用作行索引的列编号或者列名,如果给定一个序列则有多个行索引。 如果文件不规则,行尾有分隔符,则可以设定index_col=False 来是的pandas不适用第一列作为行索引。parse_dates: boolean or list of ints or names or list of lists or dict, default False boolean. True -> 解析索引 list of ints or names. e.g. If [1, 2, 3] -> 解析1,2,3列的值作为独立的日期列; list of lists. e.g. If [[1, 3]] -> 合并1,3列作为一个日期列使用 dict, e.g. {‘foo’ : [1, 3]} -> 将1,3列合并,并给合并后的列起名为"foo"sep:指定分隔符,如果不指定参数,则会尝试使用逗号分隔。dayfirst : boolean, default False DD/MM格式的日期类型skiprows : list-like or integer, default None 需要忽略的行数(从文件开始处算起),或需要跳过的行号列表(从0开始)。names : array-like, default None 列名
最新回复(0)