1

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

这是我一直在使用的一个示例。(注意,a['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, '%s')

理想情况下,我想要的东西可以产生这样的文件:http ://www.antarctica.ac.uk/data/absl/ABSL-index-Monthly-ERA-Interim_Hosking2013.txt

我现在找到了这个问题的答案,请参阅以下内容...... https://stackoverflow.com/a/19676112/1310153

4

4 回答 4

2

尝试这个:

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是字段宽度。

于 2013-10-29T15:17:38.257 回答
2

您可以执行以下操作:

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'))

或者:

np.savetxt('test.txt', a, fmt='%-12s')

然后你有数据上方的列名。

于 2013-10-29T15:22:16.637 回答
1

如果你想要,比如说,每个元素之间有两个标签,你可以这样做:

>>> 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 的评论,您可以使用 pandas:

import pandas as pd
pd.DataFrame(a).to_csv('testfile.txt',sep='\t')
于 2013-10-29T15:22:37.633 回答
0

我现在找到了一种巧妙的方法,可以使用与列数据相同的格式来包含标题。感谢大家的帮助。

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')
于 2013-10-30T07:19:57.053 回答