Home > Software engineering >  Error while turning a string into a tuple
Error while turning a string into a tuple

Time:07-01

This is for Jupyter Notebook/Google Colab/Pandas the full number of my Latitude isn't showing up when I would run the code to convert a strong to a tuple. Output before I ran the code

Code I ran

#convert LATLNG from string to tuple
new_LNGLAT=[]
for i in range(len(df)):
    a=df['LATLNG'].iloc[i]
    new_LNGLAT.append((float(a[a.find(':') 2:a.find(',')]),float(a[a.find('-'):a.find('}')])))

df['LATLNG']=new_LNGLAT

Output of dataframe after I ran the code

Anyone know how to fix

CodePudding user response:

Your code seems to be trying to extract from a string that't not formatted the same way that you show in the dataframe. The latitude and longitude are just separated by comma, there's no : or } characters. You can use the split() function to separate this.

for i in range(len(df)):
    a=df['LATLNG'].iloc[i]
    lat, lon = a.split(',')
    new_LNGLAT.append((float(lat),float(lon)))

CodePudding user response:

You can try apply a lambda function:

df['LATLNG'] = df['LATLNG'].apply(lambda x: x.split(',')) #This return a list
df['LATLNG'] = df['LATLNG'].apply(lambda x: tuple(x)) #Transform the list to tuple

Also this will work:

df['LATLNG'] = df['LATLNG'].apply(lambda x: tuple(x.split(',')))

CodePudding user response:

df['LATLNG'] = df['LATLNG'].str.split(',').apply(tuple)
  • Related