gpt4 book ai didi

python - 将带有数组的列表从 csv 文件转换为 float

转载 作者:行者123 更新时间:2023-11-28 17:26:48 28 4
gpt4 key购买 nike

我有一个 csv 文件,其中包含加速度计和陀螺仪数据的各种参数的样本列表。它包含 float (IQR、Range、MAD、...)和数组(ZCD 值)。当我读回它时,它们以字符串形式返回,对于我的处理,我需要数字(int/float)。我试过了

    results = map(int, results)

results = [int(i) for i in results]

我从 here 得到它们,但我遇到了数组问题。

Traceback (most recent call last):
File "/home/pi/Desktop/imu/mpu_v16.py", line 458, in <module>
main()
File "/home/pi/Desktop/imu/mpu_v16.py", line 439, in main
compare()
File "/home/pi/Desktop/imu/mpu_v16.py", line 305, in compare
nrow = [float(i) for i in nrow]
ValueError: could not convert string to float: [ 53 73 79 139]

我该如何解决这个问题?

我正在添加我的数据样本:

    C,3.3440452548950501e-17,0.99999999999999645,0.89244290726827058,1.7947499048650259,3.3651560716219242,[108 123 149 220 235],0.99999999999999822,110223.99999999971,331.99999999999915,-5.9524005537131887e-17,0.99999999999999989,0.81051947660768831,1.4756039753111405,4.4268119259334213,[103 122 160 205 212],0.99999999999999989,110224.00000000001,332.00000000000006,-6.4540073419474463e-17,0.999999999999999,0.74198651253618131,0.63512619216067612,4.256170326687128,[106 164 192 226],0.99999999999999933,110224.00000000001,332.00000000000006,2.083131190971185e-16,1.0000000000000009,0.66659374901400581,0.52759419283475883,4.5104130995285256,[  7  14  45  56 150 327],1.0000000000000002,110223.99999999994,331.99999999999983,-3.0890618042093025e-17,0.99999999999999667,0.58289607514346964,0.21669963911591134,4.7919240951669444,[ 82 149 208],0.99999999999999822,110223.99999999942,331.99999999999824,-3.2771643497971487e-16,1.0000000000000009,0.58746356061392535,0.29681486739557372,5.2741718744905794,[ 26  48  59  66 114 171 231 242],1.0000000000000002,110224.00000000036,332.00000000000108,-0.57536274345915739,0.147595080030029,0.13018399571123057

最佳答案

您的 csv 格式不正确,或者您读取的内容不正确。您提取的不是单个数字,而是方括号中的多个数字。查看错误信息:

ValueError: could not convert string to float: [ 53  73  79 139]
### This is your data ^ ^

所以当你实际上应该有 [["53", "73 ", "79", "139"], ["123", "12", "11"]]["53", "73", "79", "139", “123”、“12”、“11”]

如果您的 csv 格式不正确,您可以通过拆分错误值来即时更正此问题。这将为您提供一个平面列表,如 [53, 73, 79, 139]:

nrow = [float(i) for elem in nrow for i in elem.strip('[] ').split()]
# ^ ^ extract every sequence of numbers
# ^ ^ remove [] and whitespace around sequences
# ^ ^ split the actual numbers

这将为您提供一个列表列表,例如 [[ 53, 73, 79, 139], ...]:

    nrow = [[float(i) for i in elem.strip('[] ').split()] for elem in nrow ]

关于python - 将带有数组的列表从 csv 文件转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38247354/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com