【硬核干貨】Pandas模塊中的數(shù)據(jù)類(lèi)型轉(zhuǎn)換

Pandas模塊當(dāng)中的數(shù)據(jù)類(lèi)型轉(zhuǎn)換的相關(guān)技巧,干貨滿(mǎn)滿(mǎn)的哦!導(dǎo)入數(shù)據(jù)集和模塊
那么我們第一步慣例就是導(dǎo)入Pandas模塊以及創(chuàng)建數(shù)據(jù)集了,代碼如下
import pandas as pd
import numpy as np
df = pd.DataFrame({
'string_col': ['1','2','3','4'],
'int_col': [1,2,3,4],
'float_col': [1.1,1.2,1.3,4.7],
'mix_col': ['a', 2, 3, 4],
'missing_col': [1.0, 2, 3, np.nan],
'money_col': ['£1,000.00', '£2,400.00', '£2,400.00', '£2,400.00'],
'boolean_col': [True, False, True, True],
'custom': ['Y', 'Y', 'N', 'N']
})
df
output

我們先來(lái)看一下每一列的數(shù)據(jù)類(lèi)型,代碼如下
df.dtypes
output
string_col object
int_col int64
float_col float64
mix_col object
missing_col float64
money_col object
boolean_col bool
custom object
dtype: object
當(dāng)然了我們也可以調(diào)用info()方法來(lái)實(shí)現(xiàn)上述的目的,代碼如下
df.info()
output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 string_col 4 non-null object
1 int_col 4 non-null int64
2 float_col 4 non-null float64
3 mix_col 4 non-null object
4 missing_col 3 non-null float64
5 money_col 4 non-null object
6 boolean_col 4 non-null bool
7 custom 4 non-null object
dtypes: bool(1), float64(2), int64(1), object(4)
memory usage: 356.0+ bytes
數(shù)據(jù)類(lèi)型轉(zhuǎn)換
astype()方法,例如我們將浮點(diǎn)型的數(shù)據(jù)轉(zhuǎn)換成整型,代碼如下df['float_col'] = df['float_col'].astype('int')
或者我們將其中的“string_col”這一列轉(zhuǎn)換成整型數(shù)據(jù),代碼如下
df['string_col'] = df['string_col'].astype('int')
當(dāng)然我們從節(jié)省內(nèi)存的角度上來(lái)考慮,轉(zhuǎn)換成int32或者int16類(lèi)型的數(shù)據(jù),
df['string_col'] = df['string_col'].astype('int8')
df['string_col'] = df['string_col'].astype('int16')
df['string_col'] = df['string_col'].astype('int32')
然后我們?cè)賮?lái)看一下轉(zhuǎn)換過(guò)后的各個(gè)列的數(shù)據(jù)類(lèi)型
df.dtypes
output
string_col float32
int_col int64
float_col int32
mix_col object
missing_col float64
money_col object
boolean_col bool
custom object
dtype: object
但是當(dāng)某一列的數(shù)據(jù)類(lèi)型不止一個(gè)的時(shí)候,轉(zhuǎn)換的過(guò)程當(dāng)中則會(huì)報(bào)錯(cuò),例如“mix_col”這一列
df['mix_col'] = df['mix_col'].astype('int')
output
ValueError: invalid literal for int() with base 10: 'a'
于是乎我們可以調(diào)用的to_numeric()方法以及errors參數(shù),代碼如下
df['mix_col'] = pd.to_numeric(df['mix_col'], errors='coerce')
df
output

而要是遇到缺失值的時(shí)候,進(jìn)行數(shù)據(jù)類(lèi)型轉(zhuǎn)換的過(guò)程中也一樣會(huì)出現(xiàn)報(bào)錯(cuò),代碼如下
df['missing_col'].astype('int')
output
ValueError: Cannot convert non-finite values (NA or inf) to integer
我們可以先通過(guò)調(diào)用fillna()方法來(lái)將缺失值填充成其他數(shù)值,然后再進(jìn)行類(lèi)型的轉(zhuǎn)換,代碼如下
df["missing_col"] = df["missing_col"].fillna(0).astype('int')
df
output

最后的則是“money_col”這一列,我們看到當(dāng)中有貨幣符號(hào),因此第一步我們要做的則是將這些貨幣符號(hào)給替換掉,然后再進(jìn)行數(shù)據(jù)類(lèi)型的轉(zhuǎn)換,代碼如下
df['money_replace'] = df['money_col'].str.replace('£', '').str.replace(',','')
df['money_replace'] = pd.to_numeric(df['money_replace'])
df['money_replace']
output
0 1000.0
1 2400.0
2 2400.0
3 2400.0
當(dāng)遇上時(shí)間序列數(shù)據(jù)時(shí)
to_datetime()方法,代碼如下df = pd.DataFrame({'date': ['3/10/2015', '3/11/2015', '3/12/2015'],
'value': [2, 3, 4]})
df
output

我們先來(lái)看一下各個(gè)列的數(shù)據(jù)類(lèi)型
df.dtypes
output
date object
value int64
dtype: object
我們調(diào)用to_datetime()方法的代碼如下
pd.to_datetime(df['date'])
output
0 2015-03-10
1 2015-03-11
2 2015-03-12
Name: date, dtype: datetime64[ns]
當(dāng)然這并不意味著不能調(diào)用astype()方法了,出來(lái)的結(jié)果與上述的一樣,代碼如下
df['date'].astype('datetime64')
而當(dāng)我們遇到自定義格式的日期格式的數(shù)據(jù)時(shí),同樣也是調(diào)用to_datetime()方法,但是需要設(shè)置的格式也就是format參數(shù)需要保持一致
df = pd.DataFrame({'date': ['2016-6-10 20:30:0',
'2016-7-1 19:45:30',
'2013-10-12 4:5:1'],
'value': [2, 3, 4]})
df['date'] = pd.to_datetime(df['date'], format="%Y-%d-%m %H:%M:%S")
output

是不是可以一步到位呢?
最后,或許有人會(huì)問(wèn),是不是有什么辦法可以一步到位實(shí)現(xiàn)數(shù)據(jù)類(lèi)型的轉(zhuǎn)換呢?那當(dāng)然也是可以實(shí)現(xiàn)的,代碼如下
df = pd.DataFrame({'date_start': ['3/10/2000', '3/11/2000', '3/12/2000'],
'date_end': ['3/11/2000', '3/12/2000', '3/13/2000'],
'string_col': ['1','2','3'],
'float_col': [1.1,1.2,1.3],
'value': [2, 3, 4]})
df = df.astype({
'date_start': 'datetime64',
'date_end': 'datetime64',
'string_col': 'int32',
'float_col': 'int64',
'value': 'float32',
})
我們來(lái)看一下出來(lái)的結(jié)果
df
output



