簡體   English   中英

如何使用 python 將列中的 dtype 從 object 更改為 float64?

[英]How can i change dtype from object to float64 in a column, using python?

我從投資中提取了一些數據,但列值都是dtype = object ,所以我不能使用它們......我應該如何將 object 轉換為 float

( 2558 6.678,08 2557 6.897,23 2556 7.095,95 2555 7.151,21 2554 7.093,34... 4 4.050,38 3 4.042,63 2 4.181,13 1 4.219,56 0 4.223,33 Name: Alta, Length: 2559, dtype: object

我想要的是: 2558 6678.08 2557 6897.23 2556 7095.95 2555 7151.21 2554 7093.34... 4 4050.38 3 4042.63 2 4181.13 1 4219.56 0 4223.33 Name: Alta, Length: 2559, dtype: float

試圖使用 function 來代替,因為。

def clean(x): x = x.replace(".", "").replace(",",".")

但它不起作用,因為 dtype 是 object

謝謝!

參考: 如何在 python 中將數據類型:object 轉換為 float64?

for i in range(0, len(df.columns)):
    df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
    # errors='ignore' lets strings remain as 'non-null objects'

這可以將所有數值轉換為 float64 或 int64。

要替換您的值,請嘗試此操作。 結果是您的 dataframe,col 是您的列名

result[col] = result[col].apply(lambda x: x.str.replace(".","").str.replace(",","."))

如果您需要將此變量轉換為浮點數,請嘗試此操作

result[col] = result[col].astype(float)

如果您的本地語言環境使用逗號作為十進制符號,您可以使用locale.atof (如果不是,您首先必須設置適當的語言環境):

>>> s = pd.Series(['6.678,08','6.897,23'], name='Alta')
>>> s
0    6.678,08
1    6.897,23
Name: Alta, dtype: object
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, '')
'de_DE.UTF-8'
>>> s.apply(locale.atof)
0    6678.08
1    6897.23
Name: Alta, dtype: float64

那是因為value之間有一個逗號 因為float不能有逗號,所以需要先把逗號替換掉再轉成float result[col] = result[col].str.replace(","," ").astype(浮動)

暫無
暫無

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

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