简体   繁体   中英

How to convert a string in pandas dataframe into float or int

I have csv file, it looks like this: 在此处输入图像描述

The values of the first column 'Polygon' are strings. I would like to convert them into a sequence of nested lists, eg [[[1051381.5487, 7320839.9048], [1051368.1571, 7320819.7107],...]]].

To make it easier to understand I take only first 5 rows of the column:

polygon = pd.DataFrame(germ.iloc[:5,0])

So it looks:

在此处输入图像描述

When I try to take the first row and to apply.astype(float)/.astype(int) it returns me this error:

ValueError: could not convert string to float: '[[[1051381.5487 7320839.9048]\n [1051368.1571 7320819.7107]\n [1051343.0323 7320781.7935]\n [1051309.9702 7320722.5248]\n [1051296.0555 7320689.1256]\n [1051278.0215 7320615.9572]\n [1051263.9953 7320445.8771]\n [1051260.4331 7320392.016 ]\n [1051184.068 7320399.352 ]\n [1051168.8172 7320476.7657]\n [1051126.5157 7320604.76 ]\n [1051098.3519 7320670.2061]\n [1051051.9317 7320733.5289]\n [1051014.9038 7320825.1753]\n [1051007.6265 7320843.1868]\n [1050998.81 7320865.8909]\n [1050991.3741 7320885.0811]\n [1050986.9211 7320934.5052]\n [1050962.6534 7320983.3505]\n [1050949.0725 7321018.2951]\n [1050944.6197 7321061.3489]\n [1050947.8481 7321075.4429]\n [1050947.7366 7321104.4028]\n [1050939.0538 7321143.0166]\n [1050952.9687 7321178.7342]\n [1050981.8005 7321221.7889]\n [1050994.7134 7321231.4424]\n [1051036.5695 7321236.8484]\n [1051075.1974 7321267.1606]\n [1051106.2556 7321282.0271]\n [1051123.6215 7321240.3235]\n [1051152.7872 7321191.09 07]\n [1051195.8679 7321126.6056]\n [1051245.0709 7321050.7303]\n [1051252.9745 7321038.3741]\n [1051312.308 7320946.8614]\n [1051362.9027 7320868.7095]\n [1051381.5487 7320839.9048]]]'

Please help

Seems like the values are strings, that's why you couldn't convert them.

Perhaps try

import ast
ast.literal_eval(insert your value/string here)

Check if string

def perfectEval(anonstring):
    try:
        ev = ast.literal_eval(anonstring)
        return ev
    except ValueError:
        corrected = "\'" + anonstring + "\'"
        ev = ast.literal_eval(corrected)
        return ev

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM