【问题标题】:Pandas convert data type from object to floatPandas 将数据类型从对象转换为浮点数
【发布时间】:2021-09-27 00:31:41
【问题描述】:

我从.csv 文件中读取了一些天气数据作为名为“天气”的数据框。问题是其中一列的数据类型是object。这很奇怪,因为它表示温度。如何将其更改为具有 float 数据类型?我试过to_numeric,但是解析不出来。

weather.info()
weather.head()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 304 entries, 2017-01-01 to 2017-10-31
Data columns (total 2 columns):
Temp    304 non-null object
Rain    304 non-null float64
dtypes: float64(1), object(1)
memory usage: 17.1+ KB

           Temp     Rain
Date        
2017-01-01  12.4    0.0
2017-02-01  11      0.6
2017-03-01  10.4    0.6
2017-04-01  10.9    0.2
2017-05-01  13.2    0.0

【问题讨论】:

  • 我认为看看为什么这是一个对象可能会有所回报。该专栏有什么不寻常的地方吗?
  • 我建议添加 pandas 标志并将其添加到描述中,因为它与普通 Python 无关。
  • @WillemVanOnsem 这是我做的第一件事!这是一个简单的 csv 文件。这些数字看起来和雨柱没什么不同……

标签: python pandas


【解决方案1】:
  • 您可以使用pandas.Series.astype
  • 你可以这样做:

    weather["Temp"] = weather.Temp.astype(float)
    
  • 您还可以使用pd.to_numeric 将列从对象转换为浮点数

  • 有关如何使用它的详细信息,请查看此链接:http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • 例子:

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • 输出:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • 在你的情况下,你可以这样做:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • 其他选项是使用convert_objects
  • 示例如下

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • 您可以按如下方式使用它:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • 我已经向您展示了示例,因为如果您的任何列没有数字,那么它将被转换为NaN...所以在使用它时要小心。

【讨论】:

    【解决方案2】:

    我尝试了这里建议的所有方法,但遗憾的是没有一个奏效。相反,发现这是有效的:

    df['column'] = pd.to_numeric(df['column'],errors = 'coerce')
    

    然后使用:

    print(df.info())
    

    【讨论】:

      【解决方案3】:

      我最终使用了:

      weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)
      

      它工作得很好,除了我收到以下消息。

      C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
      convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
      

      【讨论】:

      • 嗯,为什么要使用它?需要weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
      • 是的,谢谢!完美地工作。有什么解释?
      • 警告:convert_objects 已弃用
      【解决方案4】:

      您可以尝试以下方法:

      df['column'] = df['column'].map(lambda x: float(x))
      

      【讨论】:

        【解决方案5】:

        首先检查您的数据,因为如果您使用 ',' 而不是 '.' 可能会出错 如果是这样,您需要将每个“,”转换为“。”有一个功能:

        def replacee(s):
        i=str(s).find(',')
        if(i>0):
            return s[:i] + '.' + s[i+1:]
        else :
            return s 
        

        那么您需要在列中的每一行上应用此函数:

        dfOPA['Montant']=dfOPA['Montant'].apply(replacee)
        

        那么转换函数就可以正常工作了:

        dfOPA['Montant'] = pd.to_numeric(dfOPA['Montant'],errors = 'coerce')
        

        【讨论】:

          【解决方案6】:

          例如,将 $40,000.00 object 转换为 40000 intfloat32

          一步一步来:

          $40,000.00 ---(**1**. remove $)--->  40,000.00  ---(**2**. remove , comma)--->  40000.00 ---(**3**. remove . dot)--->  4000000  ---(**4**. remove empty space)---> 4000000  ---(**5**. Remove NA Values)--->  4000000 ---(**6**. now this is object type so, convert to int using .astype(int) )---> 4000000  ---(**7**. divide by 100)---> 40000  
          

          在 Pandas 中实现代码

          table1["Price"] = table1["Price"].str.replace('$','')<br>
          table1["Price"] = table1["Price"].str.replace(',','')<br>
          table1["Price"] = table1["Price"].str.replace('.','')<br>
          table1["Price"] = table1["Price"].str.replace(' ','')     
          table1 = table1.dropna()<br>
          table1["Price"] = table1["Price"].astype(int)<br>
          table1["Price"] = table1["Price"] / 100<br> 
          

          终于搞定了

          【讨论】:

          • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 2021-08-11
          • 1970-01-01
          • 2022-11-21
          • 1970-01-01
          • 2018-12-09
          • 1970-01-01
          • 2019-01-11
          • 2022-01-26
          • 1970-01-01
          相关资源
          最近更新 更多