如何在Python中创建包含标题(文本)和填充值(int和float)的表
我正在用python填充一个numpy数组(如果必要的话,可以将其更改为列表),我想用列标题填充它,然后输入一个循环并用值填充表,我正在努力为数组使用哪种类型。到目前为止我有类似的事情如何在Python中创建包含标题(文本)和填充值(int和float)的表,python,arrays,string,csv,numpy,Python,Arrays,String,Csv,Numpy,我正在用python填充一个numpy数组(如果必要的话,可以将其更改为列表),我想用列标题填充它,然后输入一个循环并用值填充表,我正在努力为数组使用哪种类型。到目前为止我有类似的事情 info = np.zeros(shape=(no_of_label+1,19),dtype = np.str) #Creates array to store coordinates of particles info[0,:] = ['Xpos','Ypos','Zpos','NodeN
info = np.zeros(shape=(no_of_label+1,19),dtype = np.str) #Creates array to store coordinates of particles
info[0,:] = ['Xpos','Ypos','Zpos','NodeNumber','BoundingBoxTopX','BoundingBoxTopY','BoundingBoxTopZ','BoundingBoxBottomX','BoundingBoxBottomY','BoundingBoxBottomZ','BoxVolume','Xdisp','Ydisp','Zdisp','Xrot','Yrot','Zrot','CC','Error']
for i in np.arange(1,no_of_label+1,1):
info[i,:] = [C[0],C[1],C[2],i,int(round(C[0]-b)),int(round(C[1]-b)),int(round(C[2]-b)),int(round(C[0]+b)),int(round(C[1]+b)),int(round(C[2]+b)),volume,0,0,0,0,0,0,0,0] # Fills an array with label.No., size of box, and co-ords
np.savetxt(save_path+Folder+'/Data_'+Folder+'.csv',information,fmt = '%10.5f' ,delimiter=",")
循环中还有其他东西,但它们是无关的,C是浮点数组,b是int
我还需要能够将其保存为csv文件,如最后一行所示,并在excel中打开它
现在,当我需要C[0],C[1],C[2]作为浮点时,我将所有的值作为整数返回
提前谢谢 这取决于你想用这个数组做什么,但我认为你想用'dtype=object'而不是'np.str'。您可以通过将“np.str”更改为“dtype”来显式地执行此操作,或者以下是我将如何编写代码的第一部分:
import numpy as np
labels = ['Xpos','Ypos','Zpos','NodeNumber','BoundingBoxTopX','BoundingBoxTopY',
'BoundingBoxTopZ','BoundingBoxBottomX','BoundingBoxBottomY','BoundingBoxBottomZ',
'BoxVolume','Xdisp','Ydisp','Zdisp','Xrot','Yrot','Zrot','CC','Error']
no_of_label = len(labels)
#make a list of length ((no_of_label+1)*19) and convert it to an array and reshape it
info = np.array([None]*((no_of_label+1)*19)).reshape(no_of_label+1, 19)
info[0] = labels
同样,如果您考虑了一个特定的应用程序,可能有更好的方法来实现这一点,但这应该允许您在同一个2D数组中存储不同类型的数据 我已经解决了这个问题,如下所示:
info = np.zeros(shape=(no_of_label+1,19),dtype=float)
for i in np.arange(1,no_of_label+1,1):
info[i-1] = [C[0],C[1],C[2],i,int(round(C[0]-b)),int(round(C[1]-b)),int(round(C[2]-b)),int(round(C[0]+b)),int(round(C[1]+b)),int(round(C[2]+b)),volume,0,0,0,0,0,0,0,0]
np.savetxt(save_path+Folder+'/Data_'+Folder+'.csv',information,fmt = '%10.5f' ,delimiter=",",header='Xpos,Ypos,Zpos,NodeNumber,BoundingBoxTopX,BoundingBoxTopY,BoundingBoxTopZ,BoundingBoxBottomX,BoundingBoxBottomY,BoundingBoxBottomZ,BoxVolume,Xdisp,Ydisp,Zdisp,Xrot,Yrot,Zrot,CC,Error',comments='')
使用numpy保存文本功能内置的标题功能。谢谢大家 您知道,当您保存为CSV文件时,您是在保存文本-CSV文件是文本。是的,我意识到,该过程的下一步是输入CSV文件,它需要完全按照规定的格式,谢谢。是的,dtype对象很有魅力,非常感谢!实际上,当我尝试另存为cvs文件时,您的建议给了我这个错误..%(str(X.dtype),format))类型错误:数组数据类型(“对象”)与格式说明符(“%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f、%10.5f%)之间不匹配