[英]creating text file with multiple arrays of mixed types python
I am trying to create a text file with multiple array as the columns in this file. 我正在尝试创建一个具有多个数组的文本文件作为此文件中的列。 The trick is that each array is a different datatype.
诀窍是每个数组都是不同的数据类型。 For example:
例如:
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')
However, I get an error: 但是,我得到一个错误:
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')
Any ideas? 有任何想法吗? Thanks!
谢谢!
I recommending using pandas to accomplish this task, which can easily handle multiple data types while writing out a new text file. 我建议使用熊猫来完成此任务,该任务可以在写出新的文本文件时轻松处理多种数据类型。
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)
Opening up the .txt file reveals: 打开.txt文件将显示:
a,b,c
2,NA,99.999
2,NA,99.999
2,NA,99.999
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.