>我得到了文件,我想将数据加载到 2D 数组中。 数据是混合类型、str 和浮点数。 我想将数据加载到二维数组中 每种类型都适合。 在python中有一种优雅的简短方法可以做到这一点吗?
数据示例:
M,0.455,0.365,0.095,0.514,0.2245,0.101,0.15
M,0.35,0.265,0.09,0.2255,0.0995,0.0485,0.07
F,0.53,0.42,0.135,0.677,0.2565,0.1415,0.21
train_x = np.genfromtxt('train_x.txt', dtype=None)
[[M,0.455,0.365,0.095,0.514,0.2245,0.101,0.15 ], [M,0.35,0.265,0.09,0.2255,0.0995,0.0485,0.07],
[F,0.53,0.42,0.135,0.677,0.2565,0.1415,0.21]]
out = []
with open('train_x.txt', 'r') as f:
lines = f.readlines()
for l in lines:
out.append([float(num) if n>0 else num for n, num in enumerate(l.split(',')) ])
print(out)
这将得到你想要的:
[['M', 0.455, 0.365, 0.095, 0.514, 0.2245, 0.101, 0.15], ['M', 0.35, 0.265, 0.09, 0.2255, 0.0995, 0.0485, 0.07], ['F', 0.53, 0.42, 0.135, 0.677, 0.2565, 0.1415, 0.21]]
2D 数组。第一个是str
类型,其他元素是float
类型。