forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.pyx
1953 lines (1544 loc) · 58.6 KB
/
parser.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2012, Lambda Foundry, Inc.
# See LICENSE for the license
from libc.stdio cimport fopen, fclose
from libc.stdlib cimport malloc, free
from libc.string cimport strncpy, strlen, strcmp, strcasecmp
cimport libc.stdio as stdio
import warnings
from cpython cimport (PyObject, PyBytes_FromString,
PyBytes_AsString, PyBytes_Check,
PyUnicode_Check, PyUnicode_AsUTF8String)
from io.common import DtypeWarning
cdef extern from "Python.h":
object PyUnicode_FromString(char *v)
object PyUnicode_Decode(char *v, Py_ssize_t size, char *encoding,
char *errors)
cdef extern from "stdlib.h":
void memcpy(void *dst, void *src, size_t n)
cimport numpy as cnp
from numpy cimport ndarray, uint8_t, uint64_t
import numpy as np
cimport util
import pandas.lib as lib
import time
import os
cnp.import_array()
from khash cimport *
import sys
cdef bint PY3 = (sys.version_info[0] >= 3)
cdef double INF = <double> np.inf
cdef double NEGINF = -INF
cdef extern from "headers/stdint.h":
enum: UINT8_MAX
enum: UINT16_MAX
enum: UINT32_MAX
enum: UINT64_MAX
enum: INT8_MIN
enum: INT8_MAX
enum: INT16_MIN
enum: INT16_MAX
enum: INT32_MAX
enum: INT32_MIN
enum: INT64_MAX
enum: INT64_MIN
cdef extern from "headers/portable.h":
pass
try:
basestring
except NameError:
basestring = str
cdef extern from "parser/tokenizer.h":
ctypedef enum ParserState:
START_RECORD
START_FIELD
ESCAPED_CHAR
IN_FIELD
IN_QUOTED_FIELD
ESCAPE_IN_QUOTED_FIELD
QUOTE_IN_QUOTED_FIELD
EAT_CRNL
EAT_CRNL_NOP
EAT_WHITESPACE
EAT_COMMENT
EAT_LINE_COMMENT
FINISHED
enum: ERROR_OVERFLOW
ctypedef void* (*io_callback)(void *src, size_t nbytes, size_t *bytes_read,
int *status)
ctypedef int (*io_cleanup)(void *src)
ctypedef struct parser_t:
void *source
io_callback cb_io
io_cleanup cb_cleanup
int chunksize # Number of bytes to prepare for each chunk
char *data # pointer to data to be processed
int datalen # amount of data available
int datapos
# where to write out tokenized data
char *stream
int stream_len
int stream_cap
# Store words in (potentially ragged) matrix for now, hmm
char **words
int *word_starts # where we are in the stream
int words_len
int words_cap
char *pword_start # pointer to stream start of current field
int word_start # position start of current field
int *line_start # position in words for start of line
int *line_fields # Number of fields in each line
int lines # Number of lines observed
int file_lines # Number of file lines observed (with bad/skipped)
int lines_cap # Vector capacity
# Tokenizing stuff
ParserState state
int doublequote # is " represented by ""? */
char delimiter # field separator */
int delim_whitespace # consume tabs / spaces instead
char quotechar # quote character */
char escapechar # escape character */
char lineterminator
int skipinitialspace # ignore spaces following delimiter? */
int quoting # style of quoting to write */
# hmm =/
int numeric_field
char commentchar
int allow_embedded_newline
int strict # raise exception on bad CSV */
int expected_fields
int error_bad_lines
int warn_bad_lines
# floating point options
char decimal
char sci
# thousands separator (comma, period)
char thousands
int header # Boolean: 1: has header, 0: no header
int header_start # header row start
int header_end # header row end
void *skipset
int skip_footer
# error handling
char *warn_msg
char *error_msg
ctypedef struct coliter_t:
char **words
int *line_start
int col
void coliter_setup(coliter_t *it, parser_t *parser, int i, int start)
char* COLITER_NEXT(coliter_t it)
parser_t* parser_new()
int parser_init(parser_t *self) nogil
void parser_free(parser_t *self) nogil
int parser_add_skiprow(parser_t *self, int64_t row)
void parser_set_default_options(parser_t *self)
int parser_consume_rows(parser_t *self, size_t nrows)
int parser_trim_buffers(parser_t *self)
void debug_print_parser(parser_t *self)
int tokenize_all_rows(parser_t *self)
int tokenize_nrows(parser_t *self, size_t nrows)
int64_t str_to_int64(char *p_item, int64_t int_min,
int64_t int_max, int *error, char tsep)
uint64_t str_to_uint64(char *p_item, uint64_t uint_max, int *error)
inline int to_double(char *item, double *p_value,
char sci, char decimal, char thousands)
inline int to_complex(char *item, double *p_real,
double *p_imag, char sci, char decimal)
inline int to_longlong(char *item, long long *p_value)
inline int to_longlong_thousands(char *item, long long *p_value,
char tsep)
inline int to_boolean(char *item, uint8_t *val)
cdef extern from "parser/io.h":
void *new_mmap(char *fname)
int del_mmap(void *src)
void* buffer_mmap_bytes(void *source, size_t nbytes,
size_t *bytes_read, int *status)
void *new_file_source(char *fname, size_t buffer_size)
void *new_rd_source(object obj)
int del_file_source(void *src)
int del_rd_source(void *src)
void* buffer_file_bytes(void *source, size_t nbytes,
size_t *bytes_read, int *status)
void* buffer_rd_bytes(void *source, size_t nbytes,
size_t *bytes_read, int *status)
DEFAULT_CHUNKSIZE = 256 * 1024
# common NA values
# no longer excluding inf representations
# '1.#INF','-1.#INF', '1.#INF000000',
_NA_VALUES = [b'-1.#IND', b'1.#QNAN', b'1.#IND', b'-1.#QNAN',
b'#N/A N/A', b'NA', b'#NA', b'NULL', b'NaN',
b'nan', b'']
cdef class TextReader:
'''
# source: StringIO or file object
'''
cdef:
parser_t *parser
object file_handle, na_fvalues
bint na_filter, verbose, has_usecols, has_mi_columns
int parser_start
list clocks
char *c_encoding
cdef public:
int leading_cols, table_width, skip_footer, buffer_lines
object allow_leading_cols
object delimiter, converters, delim_whitespace
object na_values, true_values, false_values
object memory_map
object as_recarray
object header, orig_header, names, header_start, header_end
object index_col
object low_memory
object skiprows
object compact_ints, use_unsigned
object dtype
object encoding
object compression
object mangle_dupe_cols
object tupleize_cols
set noconvert, usecols
def __cinit__(self, source,
delimiter=b',',
header=0,
header_start=0,
header_end=0,
index_col=None,
names=None,
memory_map=False,
tokenize_chunksize=DEFAULT_CHUNKSIZE,
delim_whitespace=False,
compression=None,
converters=None,
as_recarray=False,
skipinitialspace=False,
escapechar=None,
doublequote=True,
quotechar=b'"',
quoting=0,
lineterminator=None,
encoding=None,
comment=None,
decimal=b'.',
thousands=None,
dtype=None,
usecols=None,
error_bad_lines=True,
warn_bad_lines=True,
na_filter=True,
na_values=None,
na_fvalues=None,
true_values=None,
false_values=None,
compact_ints=False,
allow_leading_cols=True,
use_unsigned=False,
low_memory=False,
buffer_lines=None,
skiprows=None,
skip_footer=0,
verbose=False,
mangle_dupe_cols=True,
tupleize_cols=False):
self.parser = parser_new()
self.parser.chunksize = tokenize_chunksize
self.mangle_dupe_cols=mangle_dupe_cols
self.tupleize_cols=tupleize_cols
# For timekeeping
self.clocks = []
self.compression = compression
self.memory_map = memory_map
self._setup_parser_source(source)
parser_set_default_options(self.parser)
parser_init(self.parser)
if delim_whitespace:
self.parser.delim_whitespace = delim_whitespace
else:
if len(delimiter) > 1:
raise ValueError('only length-1 separators excluded right now')
self.parser.delimiter = ord(delimiter)
#----------------------------------------
# parser options
self.parser.doublequote = doublequote
self.parser.skipinitialspace = skipinitialspace
if lineterminator is not None:
if len(lineterminator) != 1:
raise ValueError('Only length-1 line terminators supported')
self.parser.lineterminator = ord(lineterminator)
if len(decimal) != 1:
raise ValueError('Only length-1 decimal markers supported')
self.parser.decimal = ord(decimal)
if thousands is not None:
if len(thousands) != 1:
raise ValueError('Only length-1 thousands markers supported')
self.parser.thousands = ord(thousands)
if escapechar is not None:
if len(escapechar) != 1:
raise ValueError('Only length-1 escapes supported')
self.parser.escapechar = ord(escapechar)
self.parser.quotechar = ord(quotechar)
self.parser.quoting = quoting
if comment is not None:
if len(comment) > 1:
raise ValueError('Only length-1 comment characters supported')
self.parser.commentchar = ord(comment)
# error handling of bad lines
self.parser.error_bad_lines = int(error_bad_lines)
self.parser.warn_bad_lines = int(warn_bad_lines)
self.skiprows = skiprows
if skiprows is not None:
self._make_skiprow_set()
self.skip_footer = skip_footer
# suboptimal
if usecols is not None:
self.has_usecols = 1
self.usecols = set(usecols)
# XXX
if skip_footer > 0:
self.parser.error_bad_lines = 0
self.parser.warn_bad_lines = 0
self.delimiter = delimiter
self.delim_whitespace = delim_whitespace
self.na_values = na_values
if na_fvalues is None:
na_fvalues = set()
self.na_fvalues = na_fvalues
self.true_values = _maybe_encode(true_values)
self.false_values = _maybe_encode(false_values)
self.converters = converters
self.na_filter = na_filter
self.as_recarray = as_recarray
self.compact_ints = compact_ints
self.use_unsigned = use_unsigned
self.verbose = verbose
self.low_memory = low_memory
# encoding
if encoding is not None:
if not isinstance(encoding, bytes):
encoding = encoding.encode('utf-8')
encoding = encoding.lower()
self.c_encoding = <char*> encoding
else:
self.c_encoding = NULL
self.encoding = encoding
if isinstance(dtype, dict):
conv = {}
for k in dtype:
v = dtype[k]
if isinstance(v, basestring):
v = np.dtype(v)
conv[k] = v
dtype = conv
elif dtype is not None:
dtype = np.dtype(dtype)
self.dtype = dtype
# XXX
self.noconvert = set()
self.index_col = index_col
#----------------------------------------
# header stuff
self.allow_leading_cols = allow_leading_cols
self.leading_cols = 0
# TODO: no header vs. header is not the first row
self.has_mi_columns = 0
self.orig_header = header
if header is None:
# sentinel value
self.parser.header_start = -1
self.parser.header_end = -1
self.parser.header = -1
self.parser_start = 0
self.header = []
else:
if isinstance(header, list) and len(header):
# need to artifically skip the final line
# which is still a header line
header = list(header)
header.append(header[-1]+1)
self.parser.header_start = header[0]
self.parser.header_end = header[-1]
self.parser.header = header[0]
self.parser_start = header[-1] + 1
self.has_mi_columns = 1
self.header = header
else:
self.parser.header_start = header
self.parser.header_end = header
self.parser.header = header
self.parser_start = header + 1
self.header = [ header ]
self.names = names
self.header, self.table_width = self._get_header()
if not self.table_width:
raise ValueError("No columns to parse from file")
# compute buffer_lines as function of table width
heuristic = 2**20 // self.table_width
self.buffer_lines = 1
while self.buffer_lines * 2< heuristic:
self.buffer_lines *= 2
def __init__(self, *args, **kwards):
pass
def __dealloc__(self):
parser_free(self.parser)
def set_error_bad_lines(self, int status):
self.parser.error_bad_lines = status
cdef _make_skiprow_set(self):
if isinstance(self.skiprows, (int, np.integer)):
self.skiprows = range(self.skiprows)
for i in self.skiprows:
parser_add_skiprow(self.parser, i)
cdef _setup_parser_source(self, source):
cdef:
int status
void *ptr
self.parser.cb_io = NULL
self.parser.cb_cleanup = NULL
if self.compression:
if self.compression == 'gzip':
import gzip
if isinstance(source, basestring):
source = gzip.GzipFile(source, 'rb')
else:
source = gzip.GzipFile(fileobj=source)
elif self.compression == 'bz2':
import bz2
if isinstance(source, basestring):
source = bz2.BZ2File(source, 'rb')
else:
raise ValueError('Python cannot read bz2 from open file '
'handle')
else:
raise ValueError('Unrecognized compression type: %s' %
self.compression)
if isinstance(source, basestring):
if not isinstance(source, bytes):
source = source.encode(sys.getfilesystemencoding() or 'utf-8')
if self.memory_map:
ptr = new_mmap(source)
if ptr == NULL:
# fall back
ptr = new_file_source(source, self.parser.chunksize)
self.parser.cb_io = &buffer_file_bytes
self.parser.cb_cleanup = &del_file_source
else:
self.parser.cb_io = &buffer_mmap_bytes
self.parser.cb_cleanup = &del_mmap
else:
ptr = new_file_source(source, self.parser.chunksize)
self.parser.cb_io = &buffer_file_bytes
self.parser.cb_cleanup = &del_file_source
if ptr == NULL:
if not os.path.exists(source):
raise IOError('File %s does not exist' % source)
raise IOError('Initializing from file failed')
self.parser.source = ptr
elif hasattr(source, 'read'):
# e.g., StringIO
ptr = new_rd_source(source)
if ptr == NULL:
raise IOError('Initializing parser from file-like '
'object failed')
self.parser.source = ptr
self.parser.cb_io = &buffer_rd_bytes
self.parser.cb_cleanup = &del_rd_source
else:
raise IOError('Expected file path name or file-like object,'
' got %s type' % type(source))
cdef _get_header(self):
# header is now a list of lists, so field_count should use header[0]
cdef:
size_t i, start, data_line, field_count, passed_count, hr, unnamed_count
char *word
object name
int status
Py_ssize_t size
char *errors = "strict"
header = []
if self.parser.header_start >= 0:
# Header is in the file
for level, hr in enumerate(self.header):
this_header = []
if self.parser.lines < hr + 1:
self._tokenize_rows(hr + 2)
# e.g., if header=3 and file only has 2 lines
if self.parser.lines < hr + 1:
msg = self.orig_header
if isinstance(msg,list):
msg = "[%s], len of %d," % (','.join([ str(m) for m in msg ]),len(msg))
raise CParserError('Passed header=%s but only %d lines in file'
% (msg, self.parser.lines))
field_count = self.parser.line_fields[hr]
start = self.parser.line_start[hr]
# TODO: Py3 vs. Py2
counts = {}
unnamed_count = 0
for i in range(field_count):
word = self.parser.words[start + i]
if self.c_encoding == NULL and not PY3:
name = PyBytes_FromString(word)
else:
if self.c_encoding == NULL or self.c_encoding == b'utf-8':
name = PyUnicode_FromString(word)
else:
name = PyUnicode_Decode(word, strlen(word),
self.c_encoding, errors)
if name == '':
if self.has_mi_columns:
name = 'Unnamed: %d_level_%d' % (i,level)
else:
name = 'Unnamed: %d' % i
unnamed_count += 1
count = counts.get(name, 0)
if count > 0 and self.mangle_dupe_cols and not self.has_mi_columns:
this_header.append('%s.%d' % (name, count))
else:
this_header.append(name)
counts[name] = count + 1
if self.has_mi_columns:
# if we have grabbed an extra line, but its not in our format
# so save in the buffer, and create an blank extra line for the rest of the
# parsing code
if hr == self.header[-1]:
lc = len(this_header)
ic = len(self.index_col) if self.index_col is not None else 0
if lc != unnamed_count and lc-ic > unnamed_count:
hr -= 1
self.parser_start -= 1
this_header = [ None ] * lc
data_line = hr + 1
header.append(this_header)
if self.names is not None:
header = [ self.names ]
elif self.names is not None:
# Enforce this unless usecols
if not self.has_usecols:
self.parser.expected_fields = len(self.names)
# Names passed
if self.parser.lines < 1:
self._tokenize_rows(1)
header = [ self.names ]
data_line = 0
if self.parser.lines < 1:
field_count = len(header[0])
else:
field_count = self.parser.line_fields[data_line]
else:
# No header passed nor to be found in the file
if self.parser.lines < 1:
self._tokenize_rows(1)
return None, self.parser.line_fields[0]
# Corner case, not enough lines in the file
if self.parser.lines < data_line + 1:
field_count = len(header[0])
else: # not self.has_usecols:
field_count = self.parser.line_fields[data_line]
# #2981
if self.names is not None:
field_count = max(field_count, len(self.names))
passed_count = len(header[0])
# if passed_count > field_count:
# raise CParserError('Column names have %d fields, '
# 'data has %d fields'
# % (passed_count, field_count))
if self.has_usecols:
nuse = len(self.usecols)
if nuse == passed_count:
self.leading_cols = 0
elif self.names is None and nuse < passed_count:
self.leading_cols = field_count - passed_count
elif passed_count != field_count:
raise ValueError('Passed header names '
'mismatches usecols')
# oh boy, #2442, #2981
elif self.allow_leading_cols and passed_count < field_count:
self.leading_cols = field_count - passed_count
return header, field_count
cdef _implicit_index_count(self):
pass
def read(self, rows=None):
"""
rows=None --> read all rows
"""
cdef:
int status
if self.low_memory:
# Conserve intermediate space
columns = self._read_low_memory(rows)
else:
# Don't care about memory usage
columns = self._read_rows(rows, 1)
if self.as_recarray:
self._start_clock()
result = _to_structured_array(columns, self.header)
self._end_clock('Conversion to structured array')
return result
else:
return columns
cdef _read_low_memory(self, rows):
cdef:
size_t rows_read = 0
chunks = []
if rows is None:
while True:
try:
chunk = self._read_rows(self.buffer_lines, 0)
if len(chunk) == 0:
break
except StopIteration:
break
else:
chunks.append(chunk)
else:
while rows_read < rows:
try:
crows = min(self.buffer_lines, rows - rows_read)
chunk = self._read_rows(crows, 0)
if len(chunk) == 0:
break
rows_read += len(list(chunk.values())[0])
except StopIteration:
break
else:
chunks.append(chunk)
parser_trim_buffers(self.parser)
if len(chunks) == 0:
raise StopIteration
# destructive to chunks
return _concatenate_chunks(chunks)
cdef _tokenize_rows(self, size_t nrows):
cdef int status
status = tokenize_nrows(self.parser, nrows)
if self.parser.warn_msg != NULL:
print >> sys.stderr, self.parser.warn_msg
free(self.parser.warn_msg)
self.parser.warn_msg = NULL
if status < 0:
raise_parser_error('Error tokenizing data', self.parser)
cdef _read_rows(self, rows, bint trim):
cdef:
int buffered_lines
int irows, footer = 0
self._start_clock()
if rows is not None:
irows = rows
buffered_lines = self.parser.lines - self.parser_start
if buffered_lines < irows:
self._tokenize_rows(irows - buffered_lines)
if self.skip_footer > 0:
raise ValueError('skip_footer can only be used to read '
'the whole file')
else:
status = tokenize_all_rows(self.parser)
if self.parser.warn_msg != NULL:
print >> sys.stderr, self.parser.warn_msg
free(self.parser.warn_msg)
self.parser.warn_msg = NULL
if status < 0:
raise_parser_error('Error tokenizing data', self.parser)
footer = self.skip_footer
if self.parser_start == self.parser.lines:
raise StopIteration
self._end_clock('Tokenization')
self._start_clock()
columns = self._convert_column_data(rows=rows,
footer=footer,
upcast_na=not self.as_recarray)
self._end_clock('Type conversion')
self._start_clock()
if len(columns) > 0:
rows_read = len(list(columns.values())[0])
# trim
parser_consume_rows(self.parser, rows_read)
if trim:
parser_trim_buffers(self.parser)
self.parser_start -= rows_read
self._end_clock('Parser memory cleanup')
return columns
def debug_print(self):
debug_print_parser(self.parser)
cdef _start_clock(self):
self.clocks.append(time.time())
cdef _end_clock(self, what):
if self.verbose:
elapsed = time.time() - self.clocks.pop(-1)
print '%s took: %.2f ms' % (what, elapsed * 1000)
def set_noconvert(self, i):
self.noconvert.add(i)
def remove_noconvert(self, i):
self.noconvert.remove(i)
def _convert_column_data(self, rows=None, upcast_na=False, footer=0):
cdef:
Py_ssize_t i, nused
kh_str_t *na_hashset = NULL
int start, end
object name, na_flist
bint na_filter = 0
Py_ssize_t num_cols
start = self.parser_start
if rows is None:
end = self.parser.lines
else:
end = min(start + rows, self.parser.lines)
# # skip footer
# if footer > 0:
# end -= footer
#print >> sys.stderr, self.table_width
#print >> sys.stderr, self.leading_cols
#print >> sys.stderr, self.parser.lines
#print >> sys.stderr, start
#print >> sys.stderr, end
#print >> sys.stderr, self.header
#print >> sys.stderr, "index"
num_cols = -1
for i in range(self.parser.lines):
num_cols = (num_cols < self.parser.line_fields[i]) * self.parser.line_fields[i] +\
(num_cols >= self.parser.line_fields[i]) * num_cols
if self.table_width - self.leading_cols > num_cols:
raise CParserError("Too many columns specified: expected %s and found %s" %
(self.table_width - self.leading_cols, num_cols))
results = {}
nused = 0
for i in range(self.table_width):
if i < self.leading_cols:
# Pass through leading columns always
name = i
elif self.usecols and nused == len(self.usecols):
# Once we've gathered all requested columns, stop. GH5766
break
else:
name = self._get_column_name(i, nused)
if self.has_usecols and not (i in self.usecols or
name in self.usecols):
continue
nused += 1
conv = self._get_converter(i, name)
# XXX
na_flist = set()
if self.na_filter:
na_list, na_flist = self._get_na_list(i, name)
if na_list is None:
na_filter = 0
else:
na_filter = 1
na_hashset = kset_from_list(na_list)
else:
na_filter = 0
if conv:
results[i] = _apply_converter(conv, self.parser, i, start, end,
self.c_encoding)
continue
# Should return as the desired dtype (inferred or specified)
col_res, na_count = self._convert_tokens(i, start, end, name,
na_filter, na_hashset, na_flist)
if na_filter:
self._free_na_set(na_hashset)
if upcast_na and na_count > 0:
col_res = _maybe_upcast(col_res)
if issubclass(col_res.dtype.type, np.integer) and self.compact_ints:
col_res = downcast_int64(col_res, self.use_unsigned)
if col_res is None:
raise Exception('Unable to parse column %d' % i)
results[i] = col_res
self.parser_start += end - start
return results
cdef inline _convert_tokens(self, Py_ssize_t i, int start, int end,
object name, bint na_filter,
kh_str_t *na_hashset,
object na_flist):
cdef:
object col_dtype = None
if self.dtype is not None:
if isinstance(self.dtype, dict):
if name in self.dtype:
col_dtype = self.dtype[name]
elif i in self.dtype:
col_dtype = self.dtype[i]
else:
if self.dtype.names:
col_dtype = self.dtype.descr[i][1]
else:
col_dtype = self.dtype
if col_dtype is not None:
if not isinstance(col_dtype, basestring):
if isinstance(col_dtype, np.dtype):
col_dtype = col_dtype.str
else:
col_dtype = np.dtype(col_dtype).str
return self._convert_with_dtype(col_dtype, i, start, end,
na_filter, 1, na_hashset, na_flist)
if i in self.noconvert:
return self._string_convert(i, start, end, na_filter, na_hashset)
else:
col_res = None
for dt in dtype_cast_order:
try:
col_res, na_count = self._convert_with_dtype(
dt, i, start, end, na_filter, 0, na_hashset, na_flist)
except OverflowError:
col_res, na_count = self._convert_with_dtype(
'|O8', i, start, end, na_filter, 0, na_hashset, na_flist)
if col_res is not None:
break
return col_res, na_count
cdef _convert_with_dtype(self, object dtype, Py_ssize_t i,