使用多个混合类型python数组创建文本文件

时间:2016-07-18 20:15:48

标签: python arrays file numpy text

我正在尝试创建一个包含多个数组的文本文件作为此文件中的列。诀窍是每个数组都是不同的数据类型。例如:

a = np.zeros(100,dtype=np.int)+2 #integers all twos
b = QC_String = np.array(['NA']*100) #strings all 'NA'
c = np.ones(100,dtype=np.float)*99.9999 #floats all 99.9999

np.savetxt('filename.txt',[a,b,c],delimiter='\t')

然而,我收到错误:

TypeError: Mismatch between array dtype ('|S32') and format specifier   
('%.18e %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   %.18e   
%.18e')

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:2)

我建议使用pandas来完成此任务,这可以在写出新文本文件时轻松处理多种数据类型。

import numpy as np
import pandas as pd

# Create an empty DataFrame
df = pd.DataFrame()

# Populate columns in the dataframe with numpy arrays of different data types
df['a'] = np.zeros(100, dtype=np.int)+2
df['b'] = np.array(['NA']*100)
df['c'] = np.ones(100, dtype=np.float)*99.9999

# Store the data in a new text file
df.to_csv('./my_text_file.txt', index=False)

打开.txt文件会显示:

a,b,c
2,NA,99.999
2,NA,99.999
2,NA,99.999
...