简体   繁体   中英

Trouble converting strings to floats in pandas

I'm trying to to remove the percent signs and letters from two columns in pandas df. I did this by converting the percentage (which was a float) into a string and used a list comprehension with the isdigit() method to create a string that has only numbers in it. I then tried to cast that string back into an int or a float but both failed with ValueErrors saying that the conversion could not occur.

I've already tried using the astype() method, a lambda expression and applying the standard python float() and int() methods by using the pandas apply() method. They all come with the same ValueError.

Here is my code:

    def process_weather_vals(self):
        self.weatherdf['New York, NY Humidity'] = self.weatherdf['New York, NY Humidity'].astype(str)
        self.weatherdf['New York, NY Temp'] = self.weatherdf['New York, NY Temp'].astype(str)
        self.weatherdf['New York, NY Humidity'] = self.weatherdf['New York, NY Humidity'].map(lambda x: ''.join([i for i in x if i.isdigit()]))
        self.weatherdf['New York, NY Temp'] = self.weatherdf['New York, NY Temp'].map(lambda x: ''.join([i for i in x if i.isdigit()]))
        self.weatherdf['New York, NY Humidity'] = self.weatherdf['New York, NY Humidity'].apply(lambda x: float(x))
        self.weatherdf['New York, NY Temp'] = self.weatherdf['New York, NY Temp'].apply(lambda x: float(x))

I fixed it. It wasn't a code problem, my debugger was pointing to the wrong file path for the pandas libraries which caused the issues.

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