python - 替换“。” 使用 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
解决方案
普通浮点写与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 rewriting
savetxtto 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 csv
writer 也接受一个decimal
参数。
也许我应该pandas
马上看!
推荐阅读
- python - TPOT 是否支持多标签文本分类?
- c# - DataGrid内的矩形,绑定矩形的宽度值
- python - PyInstaller --noconsole 在运行应用程序后仍然显示控制台
- crosstab - 如何在 Access 中筛选交叉表查询?
- google-cloud-run - Cloud Run:自定义域的真实体验和延迟问题
- tsql - 如何在 TSQL 中将带前导零的字符串格式化为小数?
- vb.net - 数据库锁定 SQLcommand.ExecuteNonQuery() 抛出异常
- email - 为什么 Outlook 邮件中缺少“已接收”标题字段?
- javascript - 创建自定义显示布局组件
- r - 嗨,我正在尝试在 R 中创建一个对象,然后对数据进行子集化,但收到有关尺寸的错误消息