Skip to content

Commit 95ce8f1

Browse files
author
Bruno P. Kinoshita
committed
Try with cython code adapted from another function
1 parent 8787bd4 commit 95ce8f1

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

pandas/_libs/writers.pyx

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -125,19 +125,28 @@ def max_len_string_array(pandas_string[:] arr) -> Py_ssize_t:
125125

126126
for i in range(length):
127127
val = arr[i]
128-
if isinstance(val, str):
129-
l = PyString_GET_SIZE(val)
130-
elif isinstance(val, bytes):
131-
l = PyBytes_GET_SIZE(val)
132-
elif isinstance(val, unicode):
133-
l = PyUnicode_GET_SIZE(val)
128+
l = max_len_string(val)
134129

135130
if l > m:
136131
m = l
137132

138133
return m
139134

140135

136+
def max_len_string(val):
137+
""" return the maximum size of a string"""
138+
cdef:
139+
Py_ssize_t l = 0
140+
141+
if isinstance(val, str):
142+
l = PyString_GET_SIZE(val)
143+
elif isinstance(val, bytes):
144+
l = PyBytes_GET_SIZE(val)
145+
elif isinstance(val, unicode):
146+
l = PyUnicode_GET_SIZE(val)
147+
148+
return l
149+
141150
# ------------------------------------------------------------------
142151
# PyTables Helpers
143152

pandas/core/internals/blocks.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -749,8 +749,9 @@ def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
749749
mask = isna(values)
750750

751751
if not self.is_object and not quoting:
752-
if na_rep and isinstance(na_rep, str):
753-
values = values.astype("<U{length}".format(length=len(na_rep)))
752+
if na_rep is not None and isinstance(na_rep, (str, bytes)):
753+
itemsize = writers.max_len_string(na_rep)
754+
values = values.astype("<U{size}".format(size=itemsize))
754755
else:
755756
values = values.astype(str)
756757
else:

pandas/tests/io/formats/test_to_csv.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import numpy as np
55
import pytest
66

7+
from pandas.compat import StringIO
8+
79
import pandas as pd
810
from pandas import DataFrame, compat
911
from pandas.util import testing as tm

0 commit comments

Comments
 (0)