读取CSV文件以将字符串转换为float

时间:2017-02-14 18:01:36

标签: python csv

我有一个CSV文件,其格式为:

第1行:

[-0.74120803  0.6338942 ],[-1.01583889  0.20901699],[-1.02969154 0.14459244],[ 0.10362657  0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792  0.24156825],[-1.03616494  0.33943   ],[ 0.84921822  0.47879992],[ 0.279905    0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132  -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193  0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046  1.05913456],[  1.94137487e+00  -1.57339675e-03],[ 0.22311559  0.98762516],[ 2.00176133  0.13017485],......

请注意,数据有两行:第一行包含x和y坐标,第二行包含其标志状态。

第2行

0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,1,1,.......

我想将数据存储在3个列表中:xyflag。 感谢您帮助完成这一部分。

2 个答案:

答案 0 :(得分:1)

row1 = '[-0.74120803 0.6338942 ],[-1.01583889 0.20901699],[-1.02969154 0.14459244],[ 0.10362657 0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792 0.24156825],[-1.03616494 0.33943 ],[ 0.84921822 0.47879992],[ 0.279905 0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132 -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193 0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046 1.05913456],[ 1.94137487e+00 -1.57339675e-03],[ 0.22311559 0.98762516],[ 2.00176133 0.13017485]'
row2 = '0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1'

l = []

for xy, flag in zip(row1.split(','), row2.split(',')):
    x, y = xy.strip('[] ').split(' ')
    l.append((float(x), float(y), int(flag)))

print l

如果您优先选择3个单独的列表:

row1 = '[-0.74120803 0.6338942 ],[-1.01583889 0.20901699],[-1.02969154 0.14459244],[ 0.10362657 0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792 0.24156825],[-1.03616494 0.33943 ],[ 0.84921822 0.47879992],[ 0.279905 0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132 -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193 0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046 1.05913456],[ 1.94137487e+00 -1.57339675e-03],[ 0.22311559 0.98762516],[ 2.00176133 0.13017485]'
row2 = '0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1'

listX, listY = [], []

for xy in row1.split(','):
    x, y = xy.strip('[] ').split(' ')
    listX.append(float(x))
    listY.append(float(y))

listFlag = [int(flag) for flag in row2.split(',')]

print listX, listY, listFlag

答案 1 :(得分:1)

两个单行将会:

flags = [int(x) for x in row2.split(',')]
x, y = zip(*((float(value) for value in entry[1:-1].split()) for entry in row1.split(',')))

现在:

print(flags[:5])
print(list(x[:5]))
print(list(y[:5]))

输出:

[0, 0, 0, 1, 1]
[-0.74120803, -1.01583889, -1.02969154, 0.10362657, 1.69977092]
[0.6338942, 0.20901699, 0.14459244, 0.31347394, -0.13384537]