![](/img/trans.png)
[英]converting a dataframe from float64 to object using dtype
[英]Changing Dtype "object" to Dtype "float64" in DataSeries
我正在嘗試將 Dtype object 轉換為 Dtype float64。 轉換前的 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 時,我得到以下結果:
<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.