Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/Numpy—将多个1D数组以整齐的列写入文件_Python_String_File Io_Numpy - Fatal编程技术网

Python/Numpy—将多个1D数组以整齐的列写入文件

Python/Numpy—将多个1D数组以整齐的列写入文件,python,string,file-io,numpy,Python,String,File Io,Numpy,如何在python/numpy中创建一个文本文件,该文件以整齐对齐的列(即以空格分隔)并排显示多个1D数组。我还想在列的顶部包括数组的名称 这是我一直在研究的一个例子。(注意,['site']数组中的字符串具有不同的字符长度,导致列未对齐) 理想情况下,我希望能够生成如下文件: 我现在已经找到了这个问题的答案,请看下面 试试这个: import numpy as np dt = np.dtype([('site', '|S11'), ('year', 'i'), ('dat1', 'd'),

如何在python/numpy中创建一个文本文件,该文件以整齐对齐的列(即以空格分隔)并排显示多个1D数组。我还想在列的顶部包括数组的名称

这是我一直在研究的一个例子。(注意,['site']数组中的字符串具有不同的字符长度,导致列未对齐)

理想情况下,我希望能够生成如下文件:

我现在已经找到了这个问题的答案,请看下面

试试这个:

import numpy as np

dt = np.dtype([('site', '|S11'), ('year', 'i'), ('dat1', 'd'), ('dat2', 'd')])
a = np.zeros(2, dt)
a['site'] = ['Paris', 'London']
a['year'] = [1979, 1980]
a['dat1'] = [272.4322, 270.36]
a['dat2'] = [2.21, 3.55]

np.savetxt('test.txt', a, '%10s')
'%10s'
中,
10
是字段宽度。

尝试以下操作:

import numpy as np

dt = np.dtype([('site', '|S11'), ('year', 'i'), ('dat1', 'd'), ('dat2', 'd')])
a = np.zeros(2, dt)
a['site'] = ['Paris', 'London']
a['year'] = [1979, 1980]
a['dat1'] = [272.4322, 270.36]
a['dat2'] = [2.21, 3.55]

np.savetxt('test.txt', a, '%10s')

'%10s'
中,
10
是字段宽度。

您可以执行以下操作:

header = '#\n# Amundsen-Bellingshausen Seas Low (ABSL) Monthly Index\n# (based on ERA-Interim Reanalysis data)\n#\n# Dr J. Scott Hosking\n# British Antarctic Survey\n#\n# For more inforation see:\n# Hosking et al., 2013: The influence of the Amundsen-Bellingshausen Seas Low on the\n# climate of WestAntarctica and its representation in coupled climate model simulations, J.Climate\n#\n# Updated dataset can be found at: http://www.antarctica.ac.uk/data/absl/\n#\n# Key:\n#    ABSLSectorP = Area-average MSLP over ABSL sector (see Fig. 2e)\n#    ActCenPres  = Actual central pressure (i.e., ABSL Minumum MSLP)\n#    RelCenPres  = Relative central pressure (ActCenPres "minus" ABSLSectorP)\n#    ABSL_long   = Longitudinal location of ABSL (degrees East)\n#    ABSL_Lat    = Latitudinal location of ABSL\n#\n\nModel        Year  Month   ABSLSectorP   ActCenPres   RelCenPres    ABSL_long     ABSL_Lat\n'
np.savetxt('test.txt', a, header=header, fmt=('%s, %d, %f, %f'))
或:


然后在数据上方有列名。

您可以执行以下操作:

header = '#\n# Amundsen-Bellingshausen Seas Low (ABSL) Monthly Index\n# (based on ERA-Interim Reanalysis data)\n#\n# Dr J. Scott Hosking\n# British Antarctic Survey\n#\n# For more inforation see:\n# Hosking et al., 2013: The influence of the Amundsen-Bellingshausen Seas Low on the\n# climate of WestAntarctica and its representation in coupled climate model simulations, J.Climate\n#\n# Updated dataset can be found at: http://www.antarctica.ac.uk/data/absl/\n#\n# Key:\n#    ABSLSectorP = Area-average MSLP over ABSL sector (see Fig. 2e)\n#    ActCenPres  = Actual central pressure (i.e., ABSL Minumum MSLP)\n#    RelCenPres  = Relative central pressure (ActCenPres "minus" ABSLSectorP)\n#    ABSL_long   = Longitudinal location of ABSL (degrees East)\n#    ABSL_Lat    = Latitudinal location of ABSL\n#\n\nModel        Year  Month   ABSLSectorP   ActCenPres   RelCenPres    ABSL_long     ABSL_Lat\n'
np.savetxt('test.txt', a, header=header, fmt=('%s, %d, %f, %f'))
或:


然后在数据上方有列名。

如果需要,例如,在每个元素之间有两个选项卡,可以执行以下操作:

>>> with open('testfile.txt','w') as f:
    f.write('your header string')
    for x in a:
        for y in x:
            f.write(str(y)+'\t\t')
        f.write('\n')
或者,要扩展@Jan Zeiseweis的评论,您可以使用熊猫:

import pandas as pd
pd.DataFrame(a).to_csv('testfile.txt',sep='\t')

如果您想在每个元素之间设置两个选项卡,可以这样做:

>>> with open('testfile.txt','w') as f:
    f.write('your header string')
    for x in a:
        for y in x:
            f.write(str(y)+'\t\t')
        f.write('\n')
或者,要扩展@Jan Zeiseweis的评论,您可以使用熊猫:

import pandas as pd
pd.DataFrame(a).to_csv('testfile.txt',sep='\t')

现在,我发现了一种简洁的方法,可以使用与列数据相同的格式包含标题。谢谢大家的帮助

import numpy as np
dt = np.dtype([('site', '|S11'), ('year', 'i'), ('dat1', 'd'), ('dat2', 'd')])
a = np.zeros(2, dt)
a['site'] = ['Paris', 'London']
a['year'] = [1979, 1980]
a['dat1'] = [272.4322, 270.36]
a['dat2'] = [2.21, 3.55]

titles = ['Site', 'Year', 'Dat1', 'Dat2']
header = '%-12s %6s %11s %11s' % ( tuple(titles) )
header = ''+header+'\n'
np.savetxt('test.txt', a, comments='', header=header, fmt='%-12s %6i %11.4f %11.4f')

现在,我发现了一种简洁的方法,可以使用与列数据相同的格式包含标题。谢谢大家的帮助

import numpy as np
dt = np.dtype([('site', '|S11'), ('year', 'i'), ('dat1', 'd'), ('dat2', 'd')])
a = np.zeros(2, dt)
a['site'] = ['Paris', 'London']
a['year'] = [1979, 1980]
a['dat1'] = [272.4322, 270.36]
a['dat2'] = [2.21, 3.55]

titles = ['Site', 'Year', 'Dat1', 'Dat2']
header = '%-12s %6s %11s %11s' % ( tuple(titles) )
header = ''+header+'\n'
np.savetxt('test.txt', a, comments='', header=header, fmt='%-12s %6i %11.4f %11.4f')

您应该了解一下:您可以将数组放入
系列
=>数据帧中,然后放入csv文件中。或者尝试设置
np.savetxt('test.txt',a,fmt='%s',delimiter='\t')
可以通过一些调整来实现这一点,您可以给出一个输出示例吗?np.savetxt('test.txt',a,fmt='%-12s'))虽然我仍然希望在列的顶部添加名称,但仍然有效。您应该看看:您可以将数组放入
系列
=>数据帧,然后放入csv文件。或者尝试设置
np.savetxt('test.txt',a,fmt='%s',delimiter='\t')
可以通过一些调整来实现这一点,您可以给出一个输出示例吗?np.savetxt('test.txt',a,fmt='%-12s'))虽然我仍然希望在列的顶部添加名称,但仍然有效。我将使用
fmt='%-12s%d%f%f'
,这样数字的间距是自动的,但字符串的宽度是固定的。我将使用
fmt='%-12s%d%f'
这样数字的间距是自动的,但字符串的宽度是固定的。