如何使用空格分隔符从.txt文件读取数据? [英] How to read data from .txt file with whitespace delimiter?

查看:68
本文介绍了如何使用空格分隔符从.txt文件读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在文件中有每日数据,并且每日数据按月按列排列.开头带有一些文件信息.数据如下:

 日1月2月3月4月5月6月7月8月9月10月11月12月01 15.2 12.3 9.96 10.1 15.0 33.7 137309 182 62.6 27.4 17.202 14.9 12.3 9.96 9.96 16.4 38.2 109342197 69.9 25.4 16.603 14.9 12.3 9.78 10.3 17.3 50.3 118472 184 68.7 24.5 17.004 14.6 12.3 9.69 10.3 18.7 58.1 152275190 68.7 24.5 16.605 14.4 12.3 9.51 10.1 18.9 44.5 165188206 69.9 24.0 16.506 14.1 12.3 9.41 10.3 19.8 44.8 142157192 62.2 23.8 16.107 14.0 12.3 9.32 10.3 20.4 52.6 121146182 58.9 24.9 15.6 

我用这段代码读取数据

  data ='AQ404.7_01.txt'将open(data)作为fo:数据= fo.readlines()[9:41]df =数据[1:32]df = [d中d的d.strip()]df =(np.array(df))列=数据[0] [:-6]对于(df)中的字符串:df = string.split()打印df 

但是问题是,当我检查2月份的数据时,它提供了31个数据.我试图解决但无法解决.

任何人都可以帮助解决此问题吗?我还在这里附加了数据文件.

Hello I have a daily data in a file and the daily data are arranged in monthly column-wise. with some file information in the beginning. And the data looks like:

Day     Jan.   Feb.   Mar.   Apr.   May    Jun.   Jul.   Aug.   Sep.   Oct.   Nov.   Dec.   Year
 01     15.2   12.3   9.96   10.1   15.0   33.7    137    309    182   62.6   27.4   17.2
 02     14.9   12.3   9.96   9.96   16.4   38.2    109    342    197   69.9   25.4   16.6
 03     14.9   12.3   9.78   10.3   17.3   50.3    118    472    184   68.7   24.5   17.0
 04     14.6   12.3   9.69   10.3   18.7   58.1    152    275    190   68.7   24.5   16.6
 05     14.4   12.3   9.51   10.1   18.9   44.5    165    188    206   69.9   24.0   16.5
 06     14.1   12.3   9.41   10.3   19.8   44.8    142    157    192   62.2   23.8   16.1
 07     14.0   12.3   9.32   10.3   20.4   52.6    121    146    182   58.9   24.9   15.6

I used this code to read data

data ='AQ404.7_01.txt'
with open(data) as fo:
    data = fo.readlines()[9:41]
    df = data[1:32]
    df = [d.strip() for d in df]
    df = (np.array(df))
    column = data[0][:-6]
    for string in (df):
        df = string.split()
        print df

But the problem is, when I checked the data for february, It gives 31 data. I tried to solve but not able to do.

Can anyone help to solve this problem? I have also attached datafile here. https://drive.google.com/file/d/0B2rkXkOkG7ExTlJ3VnExUHFZUzA/view?usp=sharing

解决方案

You shall use Fixed Width File reader of pandas:

So for the input file you have define the list of fixed widths:

#Define the column widths    
ws = [4,9,7,7,7,7,7,7,7,7,7,7,7]

#read the file having the header row in the 9th line and read only 31 lines after that
df = pd.read_fwf('AQ404.7_01.txt',widths=ws,header=9, nrows=31)

print df

这篇关于如何使用空格分隔符从.txt文件读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆