试图从 np 数组制作一个可读的 txt 文件,所有内容都打印在一行上?
Trying to make a readable txt file from an np array, all printing on one line?
我在这里搜索了各种问题,但无法找到适当的解决方案来解决如何将我的数组保存在文本文件中以使其可读的问题。我有一个形状为 (13,5) 的 numpy 数组,其中包含 strings 。当我使用 np.savetxt 时,它全部打印在一行上。
更多数组信息:类型:class 'numpy.ndarray',条目类型:class 'numpy.str_'.
这是我用来打印数组的行:
np.savetxt('file_name.txt', array_name, fmt="%s")
为什么打印在一行上?我怎样才能使它以一种易于阅读的方式打印出来(不是全部打印在一行上)?
array_name=np.array(
[['Champion' 'Wins' 'Plays' 'Win %' 'Popularity'],
['Ahri' '17' '25' '68.0' '1.25'],
['Akali' '4' '7' '57.14' '0.35'],
['Alistar' '28' '56' '50.0' '2.8'],
['Amumu' '3' '4' '75.0' '0.2'],
['Anivia' '5' '6' '83.33' '0.3'],
['Annie' '1' '9' '11.11' '0.45'],
['Ashe' '7' '11' '63.64' '0.55'],
['Azir' '16' '28' '57.14' '1.4'],
['Bard' '19' '34' '55.88' '1.7'],
['Blitzcrank' '9' '16' '56.25' '0.8'],
['Brand' '0' '1' '0.0' '0.05'],
['Braum' '5' '16' '31.25' '0.8']])
是的,需要更多信息 -- 我无法重现您描述的内容。在 运行 这个之后:
import numpy as np
ra = np.array([['Here', 'is', 'my'],
['array', 'of', 'strings']])
np.savetxt('temp.txt', ra, fmt="%s")
文件 temp.txt
包含:
Here is my
array of strings
每行一行,每行以 '\n'
结尾,每行中的项目以空格分隔。
好的,现在您已经提供了示例数组,很容易理解为什么会得到您描述的结果:您没有用逗号分隔每行中应该是不同字符串的内容。 Python 连接相邻的字符串文字:
>>> 'a' 'b' 'c'
'abc'
因此您的数组有 1 列,而不是 5 列:
>>> array_name.shape
(13, 1)
>>> array_name[0, 0]
'ChampionWinsPlaysWin %Popularity'
>>> array_name[0, 1]
IndexError Traceback...
...
IndexError: index 1 is out of bounds for axis 1 with size 1
我在这里搜索了各种问题,但无法找到适当的解决方案来解决如何将我的数组保存在文本文件中以使其可读的问题。我有一个形状为 (13,5) 的 numpy 数组,其中包含 strings 。当我使用 np.savetxt 时,它全部打印在一行上。
更多数组信息:类型:class 'numpy.ndarray',条目类型:class 'numpy.str_'.
这是我用来打印数组的行:
np.savetxt('file_name.txt', array_name, fmt="%s")
为什么打印在一行上?我怎样才能使它以一种易于阅读的方式打印出来(不是全部打印在一行上)?
array_name=np.array(
[['Champion' 'Wins' 'Plays' 'Win %' 'Popularity'],
['Ahri' '17' '25' '68.0' '1.25'],
['Akali' '4' '7' '57.14' '0.35'],
['Alistar' '28' '56' '50.0' '2.8'],
['Amumu' '3' '4' '75.0' '0.2'],
['Anivia' '5' '6' '83.33' '0.3'],
['Annie' '1' '9' '11.11' '0.45'],
['Ashe' '7' '11' '63.64' '0.55'],
['Azir' '16' '28' '57.14' '1.4'],
['Bard' '19' '34' '55.88' '1.7'],
['Blitzcrank' '9' '16' '56.25' '0.8'],
['Brand' '0' '1' '0.0' '0.05'],
['Braum' '5' '16' '31.25' '0.8']])
是的,需要更多信息 -- 我无法重现您描述的内容。在 运行 这个之后:
import numpy as np
ra = np.array([['Here', 'is', 'my'],
['array', 'of', 'strings']])
np.savetxt('temp.txt', ra, fmt="%s")
文件 temp.txt
包含:
Here is my
array of strings
每行一行,每行以 '\n'
结尾,每行中的项目以空格分隔。
好的,现在您已经提供了示例数组,很容易理解为什么会得到您描述的结果:您没有用逗号分隔每行中应该是不同字符串的内容。 Python 连接相邻的字符串文字:
>>> 'a' 'b' 'c'
'abc'
因此您的数组有 1 列,而不是 5 列:
>>> array_name.shape
(13, 1)
>>> array_name[0, 0]
'ChampionWinsPlaysWin %Popularity'
>>> array_name[0, 1]
IndexError Traceback...
...
IndexError: index 1 is out of bounds for axis 1 with size 1