Home > OS >  How to convert a list of string into arrray of double in python3
How to convert a list of string into arrray of double in python3

Time:07-24

This is my olddata.csv:

enter image description here

I have this code:

file = open('olddata.csv')
csvreader = csv.reader(file)
kold = []
for row in csvreader:
    kold.append(row)

i get this:

print(kold)
[['1.1231'], ['1.1235'], ['1.1235'], ['1.1231'], ['1.1187'], ['1.12'], ['1.1205'], ['1.1189'], ['1.1202'], ['1.1328'], ['1.1322'], ['1.1305'], ['1.1305'], ['1.1286'], ['1.1247'], ['1.1231'], ['1.1243']]

but i want this format:

print(kold)
[1.15797091 1.15418069 1.15347472 ... 1.14577018 1.14373    1.1599099 ]

Where is the problem? I also tried list with map but it doenst work.

CodePudding user response:

This solution works for me:

file = open('olddata.csv')
csvreader = csv.reader(file)

kold = []
for row in csvreader:
    newele=row[0]
    newrow=float(newele)
    kold.append(newrow)
kold
print(kold)


[1.1151, 1.1164, 1.1162, 1.1159, 1.1159, 1.1179, 1.1208, 1.1206, 1.1231, 1.1235, 1.1235, 1.1231, 1.1187, 1.12, 1.1205, 1.1189, 1.1202, 1.1328, 1.1322, 1.1305, 1.1305, 1.1286, 1.1247, 1.1231, 1.1243]

CodePudding user response:

After you got this:

kold = [['1.1231'], ['1.1235'], ['1.1235'], ['1.1231'], ['1.1187'], ['1.12'], ['1.1205'], ['1.1189'], ['1.1202'], ['1.1328'], ['1.1322'], ['1.1305'], ['1.1305'], ['1.1286'], ['1.1247'], ['1.1231'], ['1.1243']]

You can convert it to the list of floats by using map function:

kold = list(map(lambda i: float(i[0]), kold))

CodePudding user response:

You can do the conversion directly when creating your numpy array, by specific the right dtype.

with open('olddata.csv') as file:
    csvreader = csv.reader(file)
    kold = np.array([row[0] for row in csvreader], dtype=np.double)
print(kold)

CodePudding user response:

Use the float() function to convert string to float.

  • Related