简体   繁体   中英

python pandas: try to read txt file but showed NaN

I have a txt file and I want to read it with pandas,

在此处输入图片说明

and I wrote:

#!/usr/bin/python

import pandas as pd
import numpy as np
TC=pd.read_csv('D885_Ch10_ZC.csv',error_bad_lines=False,encoding='gbk')
df=pd.DataFrame(TC,columns=['t[s]','digits[]','Ch10_zc[V]'])
print(df)

and I found the data was replace by NaN which I don't know why.

在此处输入图片说明

What goes wrong?


thx @jezrael 's answer. It works after I deleted all the useless information on the top. Is there anyway to do this without editing the original file?

I think you need sep parameter, because default is sep=',' .

if tab :

names=['t[s]','digits[]','Ch10_zc[V]']
df=pd.read_csv('D885_Ch10_ZC.csv', 
               sep='\t', 
               error_bad_lines=False,
               encoding='gbk', 
               names=names,
               skiprows=1 )

if whitespaces:

names=['t[s]','digits[]','Ch10_zc[V]']
df=pd.read_csv('D885_Ch10_ZC.csv', 
               sep='\s+',
               encoding='gbk', 
               error_bad_lines=False,
               names=names,
               skiprows=1)

names=['t[s]','digits[]','Ch10_zc[V]']
df=pd.read_csv('D885_Ch10_ZC.csv', 
               delim_whitespace=True,
               encoding='gbk',
               error_bad_lines=False,
               names=names,
               skiprows=1)

and if 2 or more whitespaces:

names=['t[s]','digits[]','Ch10_zc[V]']
df=pd.read_csv('D885_Ch10_ZC.csv', 
               sep=r'\s{2,}', 
               engine='python', 
               encoding='gbk', 
               names=names,
               skiprows=1 )

EDIT:

Need change skiprows to 10 :

names=['t[s]','digits[]','Ch10_zc[V]']
df=pd.read_csv(StringIO(temp), 
               delim_whitespace=True,
               encoding='gbk', 
               names=names,
               skiprows=10)

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