简体   繁体   中英

Reading column data from a text file in python (custom spaces as delimiter)

I am new to python and I am trying to read a space-delimited text file with spaces in the first column. The first row has to be eliminated and each of the 5 columns has to be read as a NumPy array (the scientific notation has to convert into a number). I already tried the read_table and read_csv functions of pandas but I get random results. Any insight on this would really help me.

Thanks!

My text data
在此处输入图片说明

Assuming you need a dataframe as the tags suggest and not a numpy array as the text does. And assuming the whitespace shown in the image is nothing special, this should work just fine:

from pandas import read_fwf

with open('file.txt') as f:
    next(f)
    df = read_fwf(f)

print(df)

The file is what is known as a 'fixed-width file' and that's exactly what read_fwf is for. The next() call just skips the header by reading and discarding one line from the file before passing it to read_fwf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM