Skip to main content
 首页 » 编程设计

python之genfromtxt 加载排列成行的数据

2024年11月01日7xing901022

我有以下格式的数据 csv 文件:

130, 706, 249, 627, 428, 767, 430,  63, 884, 593 
964, 340, 848, 607, 142, 517, 294, 453, 398, 236, 314, 653, 211, 439, 226 

有没有一种方法可以加载此数据,以便最终数组包含文件中数据的转置版本,并且最短列(即数据文件中最短的行)的末尾包含 nan 值?

最终结果应该是这样的:

array([[130, 964], 
[706, 340], 
[249, 848], 
[627, 607], 
[428, 142], 
[767, 517], 
[430, 294], 
[63, 453], 
[884, 398], 
[593, 236], 
[np.nan, 314],  
[np.nan, 653], 
[np.nan, 211], 
[np.nan, 439], 
[np.nan, 226]]) 

请您参考如下方法:

你可以使用itertools.izip_longest:

from itertools import izip_longest 
 
gen = (line.strip().split(',') for line in open('test.txt')) 
np.float_(list(izip_longest(*gen, fillvalue=np.nan))) 

给出:

array([[ 130.,  964.], 
       [ 706.,  340.], 
       [ 249.,  848.], 
       [ 627.,  607.], 
       [ 428.,  142.], 
       [ 767.,  517.], 
       [ 430.,  294.], 
       [  63.,  453.], 
       [ 884.,  398.], 
       [ 593.,  236.], 
       [  nan,  314.], 
       [  nan,  653.], 
       [  nan,  211.], 
       [  nan,  439.], 
       [  nan,  226.]])