python - np.loadtxt 忽略 header ,如何保存 header 数据?

标签 python numpy

我使用 savetxt 保存了一个 numpy 数组,并为该数组提供了一个 header 。当我使用 loadtxt 读取文件时,标题将被忽略,只有数据保存在我的新数组中。 我如何访问 header ,因为它包含我想保存为字符串的重要信息。

编辑:

np.savetxt(file_name, array, delimiter=",", header='x,y,z, data from monte carlo simulation')
data = np.loadtxt('test', dtype=float, delimiter=',')

我想获取“蒙特卡罗模拟数据”并将其保存为字符串。

最佳答案

要获取 header ,您只需使用文件上的 .readline() 方法读取文件的第一行即可。在你的情况下,它看起来像这样:

f = open(filename)
header = f.readline()
last_col_name = header.split(',')[-1] #returns 'data from monte carlo simulation'

此外,如果您想研究一种更通用的数据存储方式,您可以查看 pandas 库。

关于python - np.loadtxt 忽略 header ,如何保存 header 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52113401/

相关文章:

python - 如何找到二维数组满足某些条件的位置?

python - 使用 imshow 校正轴

python - Google Cloud Storage - 如何通过 Python 检索文件的所有者?

python - Django 无效 block 标记应为 'empty' 或 'endfor'

python - 尝试使用 Python 子进程进行 grep,包括引用无法找到结果

python - 用 numpy 初始化的数组在带有 if 语句的循环中要慢得多

python - 将多个 numpy 文件附加到 python 中的一个大 numpy 文件

python - sqlite python 插入

作为字典值的 Python 对象

python - Pandas 填补了 NA 但并非全部基于最近的记录