使用python从csv文件创建不同的数组

v6ylcynt  于 2023-01-08  发布在  Python
关注(0)|答案(2)|浏览(94)

我想从我的csv创建6个数组(每列一个),如下所示:
第一列是点名称(Pt_name),它包含字符串。所有其他列都包含浮点数(Hz_angle、Vz_angle、Slope_Dist、Reference_Ht、Instrument_Height)
目的是能够在浮动列的元素之间执行数学运算。
有什么想法吗?

S2,0.000000,98.799682,12.056200,1.700000,1.545000
1,0.000052,98.799806,12.056800,1.700000,1.545000
2,78.734236,99.822405,17.919000,0.000000,1.545000
3,78.861726,108.352791,17.213700,0.000000,1.545000
4,28.505234,91.249749,6.779200,0.000000,1.545000
5,34.011213,110.976488,6.840100,0.000000,1.545000
6,27.427827,106.134477,6.387900,0.000000,1.545000
48,0.926245,98.540506,25.413900,0.000000,1.545000
49,389.808941,99.812394,25.351000,0.000000,1.545000
S1,122.545107,99.563594,12.056300,1.700000,1.545000
50,200.000125,99.563463,12.058800,1.700000,1.545000
51,60.723043,95.842462,8.607300,0.000000,1.545000
0lvr5msh

0lvr5msh1#

如果你想用数组做数学运算,你应该看看numpy。要加载你的数据,你可以:

In [1]: import numpy as np

In [2]: numbers = ['Hz_angle', 'Vz_angle', 'Slope_Dist', 'Reference_Ht', 'Instrument_Height']

In [3]: dt = np.dtype([('Pt_name', np.bytes_, 5)] + [(name, np.float32) for name in numbers])

In [4]: data = np.loadtxt('/tmp/csv', delimiter=',', dtype=dt)

In [5]: data['Vz_angle']
Out[5]: 
array([  98.79968262,   98.79980469,   99.82240295,  108.35279083,
         91.24974823,  110.97648621,  106.13447571,   98.54050446,
         99.81239319,   99.563591  ,   99.5634613 ,   95.84246063], dtype=float32)

这会将文件读入dt类型的记录数组。

icnyk63a

icnyk63a2#

没有测试过,但应该可以用:

import csv

Pt_names = []
Hz_angles = []
Vz_angles = []
Slope_Dists = []
Reference_Hts = []
Instrument_Heights = []
with open(csv_file, 'r') as fh:
    reader = csv.reader(fh)
    for row in reader:
        Pt_name = row[0]
        # list comprehension for float conversion
        Hz_angle, Vz_angle, Slope_Dist, Reference_Ht, Instrument_Height = [float(value) for value in row[1:]]
        Pt_names.append(Pt_name)
        Hz_angles.append(Hz_angle)
        Vz_angles.append(Vz_angle)
        Slope_Dists.append(Slope_Dist)
        Reference_Hts.append(Reference_Ht)
        Instrument_Heights.append(Instrument_Height)

相关问题