Pandas to_csv总是用省略号替代长numpy.ndarray

9 投票
2 回答
4712 浏览
提问于 2025-04-18 17:44

我遇到了一个让人头疼的问题,涉及到pandas 0.14.0中的to_csv()函数。我在DataFrame df中有一列是很长的numpy数组:

>>> df['col'][0]    
array([   0,    1,    2, ..., 9993, 9994, 9995])
>>> len(df['col'][0])
46889
>>> type(df['col'][0][0])
<class 'numpy.int64'>

如果我用下面的方式保存df:

df.to_csv('df.csv')

然后在LibreOffice中打开df.csv时,相关的列显示成这样:

[ 0,    1,    2, ..., 9993, 9994, 9995]

而不是列出所有的46889个数字。我在想有没有什么方法可以让to_csv强制列出所有数字,而不是显示省略号?

df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 4 columns):
pair          2 non-null object
ARXscore      2 non-null float64
bselect       2 non-null bool
col           2 non-null object
dtypes: bool(1), float64(1), object(2)

2 个回答

2
np.set_printoptions(threshold='nan')

在最新版本中不太好用。请使用:

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
5

从某种意义上说,这个问题和打印整个numpy数组是重复的,因为to_csv实际上是让你的DataFrame里的每个项目都调用它的__str__方法,所以你需要看看它是怎么打印的:

In [11]: np.arange(10000)
Out[11]: array([   0,    1,    2, ..., 9997, 9998, 9999])

In [12]: np.arange(10000).__str__()
Out[12]: '[   0    1    2 ..., 9997 9998 9999]'

正如你所看到的,当超过某个阈值时,它会用省略号来表示,设置为NaN:

np.set_printoptions(threshold='nan')

举个例子:

In [21]: df = pd.DataFrame([[np.arange(10000)]])

In [22]: df  # Note: pandas printing is different!!
Out[22]:
                                                   0
0  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...

In [23]: s = StringIO()

In [24]: df.to_csv(s)

In [25]: s.getvalue()  # ellipsis
Out[25]: ',0\n0,"[   0    1    2 ..., 9997 9998 9999]"\n'

一旦改变了,to_csv就会记录整个数组:

In [26]: np.set_printoptions(threshold='nan')

In [27]: s = StringIO()

In [28]: df.to_csv(s)

In [29]: s.getvalue()  # no ellipsis (it's all there)
Out[29]: ',0\n0,"[   0    1    2    3    4    5    6    7    8    9   10   11   12   13   14\n   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29\n   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44\n   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59\n   60   61  # the whole thing is here...

如前所述,这通常不是DataFrame的好结构选择(在对象列中使用numpy数组),因为你会失去pandas的速度、效率和一些神奇的特性。

撰写回答