簡體   English   中英

pandas.read_csv:如何跳過評論行

[英]pandas.read_csv: how to skip comment lines

我想我誤解了read_csv的用意。 如果我有一個'j'文件

# notes
a,b,c
# more notes
1,2,3

我怎么能pandas.read_csv這個文件,跳過任何'#'評論的行? 我在幫助'注釋'中看到不支持行,但它表示應該返回一個空行。 我看到一個錯誤

df = pandas.read_csv('j', comment='#')

CParserError:標記數據時出錯。 C錯誤:第2行預期有1個字段,見3

我現在在

In [15]: pandas.__version__
Out[15]: '0.12.0rc1'

版本'0.12.0-199-g4c8ad82':

In [43]: df = pandas.read_csv('j', comment='#', header=None)

CParserError:標記數據時出錯。 C錯誤:第2行預期有1個字段,見3

所以我相信最新版本的pandas(版本0.16.0),你可以將comment='#'參數放入pd.read_csv ,這應該跳過注釋掉的行。

這些github問題表明你可以這樣做:

請參閱read_csv上的文檔: httpread_csv

一種解決方法是指定省略以忽略前幾個條目:

In [11]: s = '# notes\na,b,c\n# more notes\n1,2,3'

In [12]: pd.read_csv(StringIO(s), sep=',', comment='#', skiprows=1)
Out[12]: 
    a   b   c
0 NaN NaN NaN
1   1   2   3

否則read_csv有點困惑:

In [13]: pd.read_csv(StringIO(s), sep=',', comment='#')
Out[13]: 
        Unnamed: 0
a   b            c
NaN NaN        NaN
1   2            3

這似乎是0.12.0中的情況,我已經提交了一份錯誤報告

正如Viktor所指出的,你可以在事后使用dropna刪除NaN ......( 最近有一個公開的問題是完全忽略注釋行):

In [14]: pd.read_csv(StringIO(s2), comment='#', sep=',').dropna(how='all')
Out[14]: 
   a  b  c
1  1  2  3

注意:默認索引將“放棄”缺少數據的事實。

我在Pandas版本0.13.1上,這個在csv中的注釋問題仍困擾着我。

這是我目前的解決方法:

def read_csv(filename, comment='#', sep=','):
    lines = "".join([line for line in open(filename) 
                     if not line.startswith(comment)])
    return pd.read_csv(StringIO(lines), sep=sep)

否則使用pd.read_csv(filename, comment='#')我得到

pandas.parser.CParserError:標記數據時出錯。 C錯誤:第16行預期有1個字段,見3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM