日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python更改数据类型——astype()方法和to_numeric()函数

發(fā)布時(shí)間:2023/12/13 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python更改数据类型——astype()方法和to_numeric()函数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 明確指定數(shù)據(jù)的類型
    • 通過dtypes屬性進(jìn)行查看
    • 創(chuàng)建Pandas對象指定數(shù)據(jù)類型
  • 轉(zhuǎn)換數(shù)據(jù)類型
    • 通過astype()方法強(qiáng)制轉(zhuǎn)換數(shù)據(jù)的類型
    • 通過to_numeric()函數(shù)轉(zhuǎn)換數(shù)據(jù)類型


明確指定數(shù)據(jù)的類型

通過dtypes屬性進(jìn)行查看

import pandas as pddf = pd.DataFrame({'A': ['1', '2', '4'],'B': ['9', '-80', '5.3'],'C': ['x', '5.9', '0']}) print("df.dtypes:\n", df.dtypes) print("df:\n", df)

輸出結(jié)果:

df.dtypes:A object B object C object dtype: object df:A B C 0 1 9 x 1 2 -80 5.9 2 4 5.3 0

創(chuàng)建Pandas對象指定數(shù)據(jù)類型

data = pd.DataFrame({'A': ['1', '2', '4'],'B': ['9', '80', '5']},dtype='int') print("data:\n", data) print("data.dtypes:\n", data.dtypes)

輸出結(jié)果:

data:A B 0 1 9 1 2 80 2 4 5 data.dtypes:A int32 B int32 dtype: object

轉(zhuǎn)換數(shù)據(jù)類型

通過astype()方法強(qiáng)制轉(zhuǎn)換數(shù)據(jù)的類型

astype(dypte, copy=True, errors = ‘raise’, **kwargs)

上述方法中部分參數(shù)表示的含義如下:

dtype:表示數(shù)據(jù)類型

copy:是否建立副本,默認(rèn)為True

errors:錯誤采取的處理方式,可以取值為raise或ignore,默認(rèn)為raise。其中raise表示允許引發(fā)異常,ignore表示抑制異常。


運(yùn)用astype()方法將DataFrame對象df中B列數(shù)據(jù)的類型轉(zhuǎn)換為int類型:

print("df['B']:\n", df['B']) print("df['B'].astype:\n", df['B'].astype(dtype='float')) df['B']:0 9 1 -80 2 5.3 Name: B, dtype: object df['B'].astype:0 9.0 1 -80.0 2 5.3 Name: B, dtype: float64

之所以沒有將所有列進(jìn)行類型轉(zhuǎn)換是因?yàn)镃列中有非數(shù)字類型的字符,無法將其轉(zhuǎn)換為int類型,若強(qiáng)制轉(zhuǎn)換會出現(xiàn)ValueError異常。(當(dāng)參數(shù)errors取值ignore時(shí)可以抑制異常,但抑制異常后輸出結(jié)果仍是未轉(zhuǎn)換類型之前的對象——也就是并未進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換的操作,只是不會報(bào)錯罷了

print("df['C']:\n", df['C']) print("df['C'].astype(errors='ignore'):\n", df['C'].astype(dtype='float', errors='ignore'))

輸出結(jié)果:

df['C']:0 x 1 5.9 2 0 Name: C, dtype: object df['C'].astype(errors='ignore'):0 x 1 5.9 2 0 Name: C, dtype: object

通過to_numeric()函數(shù)轉(zhuǎn)換數(shù)據(jù)類型

to_numeric()函數(shù)不能直接操作DataFrame對象

pandas.to_numeric(arg, errors=‘raise’, downcast=None)

上述函數(shù)中常用參數(shù)表示的含義如下:

arg:表示要轉(zhuǎn)換的數(shù)據(jù),可以是list、tuple、Series

errors:錯誤采用的處理方式可以取值除raise、ignore外,還可以取值coerce,默認(rèn)為raise。其中raise表示允許引發(fā)異常,ignore表示抑制異常。

to_numeric()函數(shù)較之a(chǎn)stype()方法的優(yōu)勢在于解決了后者的局限性:只要待轉(zhuǎn)換的數(shù)據(jù)中存在數(shù)字以外的字符,在使用后者進(jìn)行類型轉(zhuǎn)換時(shí)就會出現(xiàn)錯誤,而to_numeric()函數(shù)之所以可以解決這個(gè)問題,就源于其errors參數(shù)可以取值coerce——當(dāng)出現(xiàn)非數(shù)字字符時(shí),會將其替換為缺失值之后進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換。


se = pd.Series(df['A']) se1 = pd.Series(df['B']) se2 = pd.Series(df['C']) print("df['A']:\n", df['A']) print("to_numeric(df['A']):\n", pd.to_numeric(se)) print("df['B']:\n", df['B']) print("to_numeric(df['B']):\n", pd.to_numeric(se1)) print("df['C']:\n", df['C']) print("to_numeric(df['C'], errors='ignore'):\n", pd.to_numeric(se2, errors='ignore')) print("to_numeric(df['C'], errors='coerce'):\n", pd.to_numeric(se2, errors='coerce'))

輸出結(jié)果:

df['A']:0 1 1 2 2 4 Name: A, dtype: object to_numeric(df['A']):0 1 1 2 2 4 Name: A, dtype: int64 df['B']:0 9 1 -80 2 5.3 Name: B, dtype: object to_numeric(df['B']):0 9.0 1 -80.0 2 5.3 Name: B, dtype: float64 df['C']:0 x 1 5.9 2 0 Name: C, dtype: object to_numeric(df['C'], errors='ignore'):0 x 1 5.9 2 0 Name: C, dtype: object to_numeric(df['C'], errors='coerce'):0 NaN 1 5.9 2 0.0 Name: C, dtype: float64

總結(jié)

以上是生活随笔為你收集整理的Python更改数据类型——astype()方法和to_numeric()函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。