簡體   English   中英

在 DataSeries 中將 Dtype“object”更改為 Dtype“float64”

[英]Changing Dtype "object" to Dtype "float64" in DataSeries

我正在嘗試將 Dtype object 轉換為 Dtype float64。 轉換前的 df 和信息請參見以下內容:

轉換前的 df

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 101 entries, 2012-01-31 to 2020-05-27
Data columns (total 1 columns):
 #   Column                                 Non-Null Count  Dtype 
---  ------                                 --------------  ----- 
 0   MSCI World Index (MXWO) - Index Value  101 non-null    object
dtypes: object(1)

然后,我應用這行代碼將“MSCI 世界指數 (MXWO) - 指數值”列轉換為 float64:

MSCI['MSCI World Index (MXWO) - Index Value']=pd.to_numeric(MSCI['MSCI World Index (MXWO) - Index Value'],errors='coerce')

當我調用 df 時,我得到以下結果:

轉換后的df

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 101 entries, 2012-01-31 to 2020-05-27
Data columns (total 1 columns):
 #   Column                                 Non-Null Count  Dtype  
---  ------                                 --------------  -----  
 0   MSCI World Index (MXWO) - Index Value  0 non-null      float64
dtypes: float64(1)

我應該對代碼做哪些更改才能正確顯示這些值,以便我可以使用這些值執行計算?

我認為你需要這種方法,對於更一般的事情來說非常方便

col_name = 'MSCI World Index (MXWO) - Index Value'
df[col_name].str.replace(',', '.', regex=True).astype(float)

Pandas 使用英文句點約定來表示十進制值。 用句點替換逗號,然后將列轉換為浮點數以解決此問題:

colname = 'MSCI World Index (MXWO) - Index Value'  # just to make the line shorter
MSCI[colname] = MSCI[colname].str.replace(',', '.').astype(float)

暫無
暫無

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

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