Python转换对象

2024-04-25 05:56:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个名为“天气”的csv文件中读取了一些天气数据。问题是其中一列的数据类型是对象。这很奇怪,因为它表明温度。。。不管怎样,我怎么把它换成浮子?我试着用数字,但它不能解析它。

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

Tags: columns文件csv数据对象object温度null
2条回答

我最终使用:

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.
  • 您可以使用pandas.Series.astype
  • 你可以这样做:

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

  • 有关如何使用它的详细信息,请签出此链接: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。。。所以在使用时要小心

  • 好好享受!!!!!!!!!!!!!!:) enter image description here

相关问题 更多 >