Home > OS >  numpy.loadtxt -> could not convert string to float: '-0,0118'
numpy.loadtxt -> could not convert string to float: '-0,0118'

Time:11-19

When I try to run this code:

x,y = np.genfromtxt('Diode_A_Upcd.txt', unpack = True,  delimiter = ';' )

I get this: Array Data My data: Diode_A_Upcd.txt

I would like to store each row in individual arrays in order to then plot them

CodePudding user response:

The error message is due to the string being 0,0118. Numpy needs floats to be 0.0118, decimal point not a decimal comma. np.loadtxt has an optional argument converters to allow a function to convert strings in one format to another.

import numpy as np                                                                                               

test_string = [ '0,123;5,234', '0,789;123,45']

def translate( s ): 
    s = s.replace( b',', b'.' ) 
    return s 

conv = { 0: translate, 1: translate } 
# Apply translate to both columns.
                                                                                                   
result = np.loadtxt( test_string, delimiter = ';', converters = conv )

result
#  array([[1.2300e-01, 5.2340e 00],
#         [7.8900e-01, 1.2345e 02]])
  • Related