gpt4 book ai didi

arrays - 将numpy数组中的元素转换为字符串

转载 作者:行者123 更新时间:2023-12-04 14:24:28 25 4
gpt4 key购买 nike

我编写了以下脚本以 numpy 数组形式从 CSV 文件加载数据:

import numpy

sample = numpy.genfromtxt('sample_cor.csv', delimiter = ',')
print sample

而这个 sample 看起来像:
[[  259463.392   2737830.062 ]
[ 255791.4823 2742050.772 ]
[ 249552.4949 2746152.328 ]
[ 247925.1228 2746422.143 ]
[ 262030.4697 2728966.229 ]
[ 260462.1936 2731412.856 ]
[ 260644.0281 2735003.027 ]
[ 268588.7974 2732835.097 ]]

现在我想将此数组中的每一行提取为带有逗号的字符串,例如,我希望将第 1 行转换为 259463.392,2737830.062 ,第 2 行是 255791.4823,2742050.772 , 等等。

我试过下面的代码:
ss = numpy.array_str(sample[0])
print ss
print type(ss)

得到的结果可能不是我想要的,
[  259463.392  2737830.062]
<type 'str'>

(我使用了 coords = '259467.2,2737833.87' 并得到了我想要的字符串形式: 259467.2,2737833.87 )

如何使用逗号将numpy数组中的元素转换为字符串?

最佳答案

这是使用 join method 的方法——

[",".join(item) for item in a.astype(str)]

sample 运行 -
In [141]: a
Out[141]:
array([[ 259463.392 , 2737830.062 ],
[ 255791.4823, 2742050.772 ],
[ 249552.4949, 2746152.328 ],
[ 247925.1228, 2746422.143 ],
[ 262030.4697, 2728966.229 ],
[ 260462.1936, 2731412.856 ],
[ 260644.0281, 2735003.027 ],
[ 268588.7974, 2732835.097 ]])

In [142]: [",".join(item) for item in a.astype(str)]
Out[142]:
['259463.392,2737830.062',
'255791.4823,2742050.772',
'249552.4949,2746152.328',
'247925.1228,2746422.143',
'262030.4697,2728966.229',
'260462.1936,2731412.856',
'260644.0281,2735003.027',
'268588.7974,2732835.097']

关于arrays - 将numpy数组中的元素转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com