簡體   English   中英

Pandas 將數據類型從 object 轉換為浮點數

[英]Pandas convert data type from object to float

我從.csv文件中讀取了一些天氣數據作為名為“天氣”的 dataframe。 問題是其中一列的數據類型是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.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 ......所以在使用它時要小心。

我嘗試了這里建議的所有方法,但遺憾的是沒有一個奏效。 相反,發現這是有效的:

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

然后使用以下方法檢查它:

print(df.info())

我最終使用了:

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.

您可以嘗試以下操作:

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

首先檢查您的數據,因為如果您使用“,”而不是“.”,您可能會收到錯誤消息。 如果是這樣,您需要將每個 ',' 轉換為 '.' 有一個功能:

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')

例如,將 $40,000.00 object轉換40000 intfloat 32

按照以下步驟操作:

$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> 

終於完成了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM