簡體   English   中英

將列表作為 txt 文件中的列寫入

[英]write lists as columns in a txt file

我想將列表寫為 txt 文件中的列。 我試着這樣做:

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'])

這會引發以下錯誤:

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')



我明白為什么這不起作用,但我不太知道如何以不同的方式來做

您正在嘗試使用字符串 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')

正如其他人指出的那樣,只有 '%s' 可以格式化它。

savetxt對數組的行進行迭代,並對其進行格式化和寫入

 fmt%tuple(row)

正如錯誤所指出的,它已將您的fmt轉換為“%s %i %i %i”。 所以它嘗試:

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

'%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'

您也可以創建結構化數組,但對象 dtype 更簡單。

zip列表方法也一樣好。

您可以使用方便的

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

試試這個,看看它是否有效:

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

%s可以處理格式中的字符串類型和整數類型。 但是要獲得更精確的格式,您可以參考我下面的鏈接。

錯誤消息告訴您的問題是您試圖將字符串類型表示為數字類型:

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

這是有關字符串格式的參考:

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

其他答案就代碼的其他方面提供了一些很好的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM