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

Python 使用混合类型的多个数组创建文本文件,python,arrays,file,numpy,text,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,

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

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')
有什么想法吗?谢谢

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

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
...

这看起来很棒!有没有办法用这个方法将它用制表符分隔而不是csv?是的,只需在写过程中添加
sep='\t'
参数:
df.to_csv('foo.txt',index=False,sep='\t')
Ok,所以我认为它已经接近了,但是我一直收到一个错误:ValueError:Length of value与Length of indexCan您可以编辑您的帖子来显示您正在运行的导致此错误的代码吗。我正在用Jupyter笔记本电脑工作,需要重新启动内核。非常感谢,成功了!