首页 > 解决方案 > 替换“。” 使用 numpy 将十进制数写入文件时使用“,”

问题描述

试图替换“。” 在我使用 numpy 编写的文件中使用“,”,但我只能成功减少整数。我怎么做?

np.savetxt("C:\\Users\\jcst\\Desktop\\Private\\Python data\\train22.csv", ('%15.1f' % predicted_factor).replace(".", ","), delimiter=',')

回溯(最近一次调用):文件“C:/Users/jcst/PycharmProjects/Frafaldsanalysis/DefiningCatAndNumFeatures_4.py”,第 165 行,在 np.savetxt("C:\Users\jcst\Desktop\Private\Python data\train22 .csv", ('%15.1f' % predict_factor).replace(".", ","), delimiter=',') TypeError: only size-1 arrays can be convert to Python scalars

标签: pythonnumpy

解决方案


普通浮点写与savetxt

In [44]: arr = np.arange(0,6,.34).reshape(6,3) 
In [51]: np.savetxt('test.txt',arr, fmt='%10.3f', delimiter=',')                
In [52]: cat test.txt                                                           
     0.000,     0.340,     0.680
     1.020,     1.360,     1.700
     2.040,     2.380,     2.720
     3.060,     3.400,     3.740
     4.080,     4.420,     4.760
     5.100,     5.440,     5.780

创建后编辑此文件,首先替换分隔符,然后替换小数点,是一种选择。

语言环境

使用该locale模块,可以将小数点更改为逗号(我假设这就是您尝试对 . 执行的操作replace)。但是我找不到一种直接使用它的方法来使用它使用%的格式样式savetxt

locale.setlocale(LC_NUMERIC):如何让它在 Windows 上工作

但是可以使用更新的format风格使用这种本地化,使用 'n' . So rewritingsavetxtto use格式`:

In [98]: fmt = '{:10.3n}'                                                       
In [99]: fmts = ';'.join([fmt]*3)+'\n'                                          
In [100]: fmts                                                                  
Out[100]: '{:10.3n};{:10.3n};{:10.3n}\n'
In [101]: with open('test1.txt','w') as f: 
     ...:     for row in arr: 
     ...:         f.write(fmts.format(*row)) 
     ...:                                                                       
In [102]: cat test1.txt                                                         
         0;      0,34;      0,68
      1,02;      1,36;       1,7
      2,04;      2,38;      2,72
      3,06;       3,4;      3,74
      4,08;      4,42;      4,76
       5,1;      5,44;      5,78

在会议的早些时候,我已经完成了

import locale    
locale.setlocale(locale.LC_NUMERIC, 'en_DK.utf8') 

我不熟悉,locale但这似乎已经足够了。我的系统上没有安装任何特殊locale软件包。

阅读

请注意,这np.genfromtxt将需要一个转换器(将逗号更改回句点)。

In [145]: foo = lambda astr: float(astr.replace(b',',b'.'))                     
In [146]: np.genfromtxt('test1.txt',delimiter=';',converters={i:foo for i in ran
     ...: ge(3)})                                                               
Out[146]: 
array([[0.  , 0.34, 0.68],
       [1.02, 1.36, 1.7 ],
       [2.04, 2.38, 2.72],
       [3.06, 3.4 , 3.74],
       [4.08, 4.42, 4.76],
       [5.1 , 5.44, 5.78]])

熊猫

pandas虽然确实有一个decimal参数:

In [133]: df = pd.read_csv('test1.txt',sep=';',decimal=',',header=None)         
In [134]: df                                                                    
Out[134]: 
      0     1     2
0  0.00  0.34  0.68
1  1.02  1.36  1.70
2  2.04  2.38  2.72
3  3.06  3.40  3.74
4  4.08  4.42  4.76
5  5.10  5.44  5.78

pandas csvwriter 也接受一个decimal参数。

也许我应该pandas马上看!


推荐阅读