zhh*_*210 6 python numpy pandas
我在处理 pandas 0.14.0 中 DataFrame 的 to_csv() 函数时遇到了一个令人作呕的问题。我有一个长 numpy 数组列表作为 DataFrame df 中的一列:
>>> df['col'][0]
array([ 0, 1, 2, ..., 9993, 9994, 9995])
>>> len(df['col'][0])
46889
>>> type(df['col'][0][0])
<class 'numpy.int64'>
Run Code Online (Sandbox Code Playgroud)
如果我通过以下方式保存 df
df.to_csv('df.csv')
Run Code Online (Sandbox Code Playgroud)
在 LibreOffice 中打开 df.csv,对应的列显示如下:
[ 0, 1, 2, ..., 9993, 9994, 9995]
Run Code Online (Sandbox Code Playgroud)
而不是列出所有 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)
Run Code Online (Sandbox Code Playgroud)
从某种意义上说,这是打印整个 numpy array的重复,因为 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]'
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,当它超过某个阈值时,它会用省略号打印,将其设置为 NaN:
np.set_printoptions(threshold='nan')
Run Code Online (Sandbox Code Playgroud)
举个例子:
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'
Run Code Online (Sandbox Code Playgroud)
一旦更改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...
Run Code Online (Sandbox Code Playgroud)
如前所述,对于 DataFrame(对象列中的 numpy 数组)来说,这通常不是一个好的结构选择,因为您会失去很多 pandas 的速度/效率/魔力。
| 归档时间: |
|
| 查看次数: |
3259 次 |
| 最近记录: |