简体   繁体   English

无法将字符串转换为大熊猫中的浮点数

[英]Trouble converting strings to floats in pandas

I'm trying to to remove the percent signs and letters from two columns in pandas df. 我正在尝试从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. 我通过将百分比(是浮点数)转换为字符串并使用带有isdigit()方法的列表理解来创建仅包含数字的字符串来做到这一点。 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. 然后,我尝试将该字符串转换回int或float形式,但都失败了,并出现ValueErrors提示无法进行转换。

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. 我已经尝试过使用astype()方法,一个lambda表达式并通过使用pandas apply()方法来应用标准的python float()和int()方法。 They all come with the same ValueError. 它们都带有相同的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. 这不是代码问题,我的调试器指向导致问题的pandas库错误的文件路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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