简体   繁体   English

将列表作为 txt 文件中的列写入

[英]write lists as columns in a txt file

I would like to write lists as columns in a txt file.我想将列表写为 txt 文件中的列。 I tried to do this like so:我试着这样做:

lst_h_names=['name_1','namenamename','nam3','4']
lst_h_1_cont=[1,2,3000,4]
lst_h_2_cont=[1,2000,3,4]
lst_scaling_factor=[10,2,3,4]
array_h_names=np.array(lst_h_names)
array_h_1_cont=np.array(lst_h_1_cont)
array_h_2_cont=np.array(lst_h_2_cont)
array_scaling_factor=np.array(lst_scaling_factor)
norm_factors=np.array([array_h_names,array_h_1_cont,array_h_2_cont,array_scaling_factor])
norm_factors=norm_factors.T
print(norm_factors)
norm_factors_path='all_factors_np.txt'
with open(norm_factors_path,'w') as fil:
    np.savetxt(fil,norm_factors,fmt=['%s','%i','%i','%i'])

This raises the following error:这会引发以下错误:

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding)
   1433                 try:
-> 1434                     v = format % tuple(row) + newline
   1435                 except TypeError:

TypeError: %i format: a number is required, not numpy.str_

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-51-5b3aeaae6c1a> in <module>
     20 norm_factors_path='all_factors_np.txt'
     21 with open(norm_factors_path,'w') as fil:
---> 22         np.savetxt(fil,norm_factors,fmt=['%s','%i','%i','%i'])

<__array_function__ internals> in savetxt(*args, **kwargs)

/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding)
   1436                     raise TypeError("Mismatch between array dtype ('%s') and "
   1437                                     "format specifier ('%s')"
-> 1438                                     % (str(X.dtype), format))
   1439                 fh.write(v)
   1440 

TypeError: Mismatch between array dtype ('<U21') and format specifier ('%s %i %i %i')



I understand why this doesn't work, but I don't quite know how to do it differently我明白为什么这不起作用,但我不太知道如何以不同的方式来做

You are trying to write an array with string dtype:您正在尝试使用字符串 dtype 编写一个数组:

In [11]: norm_factors                                                                          
Out[11]: 
array([['name_1', '1', '1', '10'],
       ['namenamename', '2', '2000', '2'],
       ['nam3', '3000', '3', '3'],
       ['4', '4', '4', '4']], dtype='<U21')

As others point out, only '%s' can format that.正如其他人指出的那样,只有 '%s' 可以格式化它。

savetxt iterates on rows of the array, and formats and writes it savetxt对数组的行进行迭代,并对其进行格式化和写入

 fmt%tuple(row)

As the error notes, it has converted your fmt into ''%s %i %i %i'.正如错误所指出的,它已将您的fmt转换为“%s %i %i %i”。 So it's try to:所以它尝试:

 '%s %i %i %i'%tuple(norm_factors[0])

An alternative to the '%s %s %s %s' is to make an object dtype array: '%s %s %s %s' 的替代方法是创建一个object dtype 数组:

In [26]: norm_factors=np.array([array_h_names,array_h_1_cont,array_h_2_cont,array_scaling_factor], dtype=object).T                                                                   
In [27]: norm_factors                                                                          
Out[27]: 
array([['name_1', 1, 1, 10],
       ['namenamename', 2, 2000, 2],
       ['nam3', 3000, 3, 3],
       ['4', 4, 4, 4]], dtype=object)
In [28]: fmt = '%s %i %i %i'                                                                   
In [29]: fmt%tuple(norm_factors[0])                                                            
Out[29]: 'name_1 1 1 10'

You could also make a structured array, but the object dtype is simpler.您也可以创建结构化数组,但对象 dtype 更简单。

And the zip lists approach is just as good. zip列表方法也一样好。

You could use which is convenient:您可以使用方便的

import pandas as pd
pd.DataFrame(norm_factors).to_csv('yourfile.txt',header=None, index=None)

Try this to see if it works:试试这个,看看它是否有效:

>>> np.savetxt(fil,norm_factors,fmt=['%s','%s','%s','%s'])

%s can handle both string types and integer types in formatting. %s可以处理格式中的字符串类型和整数类型。 But to get more precise formatting, you can refer to the link I have below.但是要获得更精确的格式,您可以参考我下面的链接。

The problem that the error message is telling you is you're trying to represent a string type as a numeric type:错误消息告诉您的问题是您试图将字符串类型表示为数字类型:

TypeError: Mismatch between array dtype ('<U21') and format specifier
('%s %i %i %i')

Here's a reference on string formatting:这是有关字符串格式的参考:

https://docs.python.org/2/library/string.html#format-specification-mini-language https://docs.python.org/2/library/string.html#format-specification-mini-language

The other answers give some good advice on other aspects of your code.其他答案就代码的其他方面提供了一些很好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM