Input:
data = [['A', 'B', 'C'], ['001', 'ddd', 'eee', '10'], ['002', 'fff', 'ggg', '20']]
Expected output:
data = ['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]]
I have attempted with the below code but I am getting this error:
ValueError: could not convert string to float: A
Could anyone point out my mistake?
formatted = []
for row in data:
new_row = []
for i, col in enumerate(row):
if i != [1,2]:
new_row.append(col)
new_row.append(float(col))
formatted.append(new_row)
print formatted
The 'pythonic' way to do this is to try converting each element to an integer, and fall back to keeping the string in case of failure.
formatted = []
for row in data:
new_row = []
for elem in row:
try:
new_row.append(int(elem))
except ValueError:
new_row.append(elem)
formatted.append(new_row)
print formatted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With