pandas-數據類型轉換


1. Pandas數據類型

pandas做數據處理,經常用到數據轉換,得到正確類型的數據。

pandas與numpy之間的數據對應關系。

重點介紹object,int64,float64,datetime64,bool等幾種類型,category與timedelta兩種類型這里不做介紹。

import numpy as np
import pandas as pd
# 從csv文件讀取數據,數據表格中只有5行,里面包含了float,string,int三種數據python類型,也就是分別對應的pandas的float64,object,int64
df = pd.read_csv("sales_data_types.csv", index_col=0)
print(df)
df.dtypes
Customer Number    float64
Customer Name       object
2016                object
2017                object
Percent Growth      object
Jan Units           object
Month                int64
Day                  int64
Year                 int64
Active              object
dtype: object
# 想得到2016年與2017年的數據總和,直接相加不是我們需要的答案,因為這兩列中的數據類型是object,執行該操作之后,得到是一個更加長的字符串,
# 通過df.info() 來獲得關於數據框的更多的詳細信息
df['2016']+df['2017']
0      $125,000.00$162500.00
1    $920,000.00$101,2000.00
2        $50,000.00$62500.00
3      $350,000.00$490000.00
4        $15,000.00$12750.00
dtype: object
df.info()
# Customer Number 列是float64,然而應該是int64
# 2016 2017兩列的數據是object,並不是float64或者int64格式
# Percent以及Jan Units 也是objects而不是數字格式
# Month,Day以及Year應該轉化為datetime64[ns]格式
# Active 列應該是布爾值
# 如果不做數據清洗,很難進行下一步的數據分析,為了進行數據格式的轉化,pandas里面有三種比較常用的方法
# 1. astype()強制轉化數據類型
# 2. 通過創建自定義的函數進行數據轉化
# 3. pandas提供的to_nueric()以及to_datetime()

 

2. Numpy中的astype()

astype()將第一列的數據轉化為整數int類型。

# 這樣的操作並沒有改變原始的數據框,而只是返回的一個拷貝
df['Customer Number'].astype("int")
0     10002
1    552278
2     23477
3     24900
4    651029
Name: Customer Number, dtype: int32
# 想要真正的改變數據框,通常需要通過賦值來進行,比如
df["Customer Number"] = df["Customer Number"].astype("int")
print(df)
print ('{:-^70}'.format('轉換后的類型:'))
print(df.dtypes)
# 然后像2016,2017 Percent Growth,Jan Units 這幾列帶有特殊符號的object是不能直接通過astype("flaot)方法進行轉化的,
# 這與python中的字符串轉化為浮點數,都要求原始的字符都只能含有數字本身,不能含有其他的特殊字符
# 我們可以試着將將Active列轉化為布爾值,看一下到底會發生什么,五個結果全是True,說明並沒有起到什么作用
df["Active"].astype("bool")
0    True
1    True
2    True
3    True
4    True
Name: Active, dtype: bool
df['2016'].astype('float')
ValueError: could not convert string to float: '$15,000.00'

以上說明:

  • 如果數據是純凈的數據,可以轉化為數字。
  • astype 兩種作用,數字轉化為單純字符串,單純數字的字符串轉化為數字,含非數字的字符串不能通過 astype 轉化。

 

3. 自定義函數清理數據

通過下面函數將貨幣進行轉化:

def convert_currency(var):
    """
    convert the string number to a float
    _ 去除$
    - 去除逗號,
    - 轉化為浮點數類型
    """
    new_value = var.replace(",","").replace("$","")
    return float(new_value)
# 通過replace函數將$以及逗號去掉,然后字符串轉化為浮點數,讓pandas選擇pandas認為合適的特定類型,float或者int,該例子中將數據轉化為了float64
# 通過pandas中的apply函數將2016列中的數據全部轉化
df["2016"].apply(convert_currency)
0    125000.0
1    920000.0
2     50000.0
3    350000.0
4     15000.0
Name: 2016, dtype: float64
# 當然可以通過lambda 函數將這個比較簡單的函數一行帶過
df["2016"].apply(lambda x: x.replace(",","").replace("$","")).astype("float64")
0    125000.0
1    920000.0
2     50000.0
3    350000.0
4     15000.0
Name: 2016, dtype: float64
#同樣可以利用lambda表達式將PercentGrowth進行數據清理
df["Percent Growth"].apply(lambda x: x.replace("%","")).astype("float")/100
0    0.30
1    0.10
2    0.25
3    0.04
4   -0.15
Name: Percent Growth, dtype: float64
# 同樣可以通過自定義函數進行解決,結果同上
# 最后一個自定義函數是利用np.where() function 將Active 列轉化為布爾值。
df["Active"] = np.where(df["Active"] == "Y", True, False)

df["Active"]
# 此時可查看一下數據格式
df["2016"]=df["2016"].apply(lambda x: x.replace(",","").replace("$","")).astype("float64")
df["2017"]=df["2017"].apply(lambda x: x.replace(",","").replace("$","")).astype("float64")
df["Percent Growth"]=df["Percent Growth"].apply(lambda x: x.replace("%","")).astype("float")/100
df.dtypes
# 再次查看DataFrame
# 此時只有Jan Units中格式需要轉化,以及年月日的合並,可以利用pandas中自帶的幾個函數進行處理
print(df)

 

4. pandas進行處理

# pandas中pd.to_numeric()處理Jan Units中的數據
pd.to_numeric(df["Jan Units"],errors='coerce').fillna(0)
0    500.0
1    700.0
2    125.0
3     75.0
4      0.0
Name: Jan Units, dtype: float64
# 最后利用pd.to_datatime()將年月日進行合並
pd.to_datetime(df[['Month', 'Day', 'Year']])
# 做到這里不要忘記重新賦值,否則原始數據並沒有變化
df["Jan Units"] = pd.to_numeric(df["Jan Units"],errors='coerce')
df["Start_date"] = pd.to_datetime(df[['Month', 'Day', 'Year']])
df
  Customer Number Customer Name 2016 2017 Percent Growth Jan Units Month Day Year Active Start_date
0 10002 Quest Industries 125000.0 162500.0 0.30 500.0 1 10 2015 True 2015-01-10
1 552278 Smith Plumbing 920000.0 1012000.0 0.10 700.0 6 15 2014 True 2014-06-15
2 23477 ACME Industrial 50000.0 62500.0 0.25 125.0 3 29 2016 True 2016-03-29
3 24900 Brekke LTD 350000.0 490000.0 0.04 75.0 10 27 2015 True 2015-10-27
4 651029 Harbor Co 15000.0 12750.0 -0.15 NaN 2 2 2014 False 2014-02-02
df.dtypes
Customer Number             int32
Customer Name              object
2016                      float64
2017                      float64
Percent Growth            float64
Jan Units                 float64
Month                       int64
Day                         int64
Year                        int64
Active                       bool
Start_date         datetime64[ns]
dtype: object
# 將這些轉化整合在一起
def convert_percent(val):
    """
    Convert the percentage string to an actual floating point percent
    - Remove %
    - Divide by 100 to make decimal
    """
    new_val = val.replace('%', '')
    return float(new_val) / 100

df_2 = pd.read_csv("sales_data_types.csv",dtype={"Customer_Number":"int"},index_col=0,converters={
    "2016":convert_currency,
    "2017":convert_currency,
    "Percent Growth":convert_percent,
    "Jan Units":lambda x:pd.to_numeric(x,errors="coerce"),
    "Active":lambda x: np.where(x=="Y",True,False)
})
df_2.dtypes
Customer Number    float64
Customer Name       object
2016               float64
2017               float64
Percent Growth     float64
Jan Units          float64
Month                int64
Day                  int64
Year                 int64
Active              object
dtype: object
df_2
  Customer Number Customer Name 2016 2017 Percent Growth Jan Units Month Day Year Active
0 10002.0 Quest Industries 125000.0 162500.0 0.30 500.0 1 10 2015 True
1 552278.0 Smith Plumbing 920000.0 1012000.0 0.10 700.0 6 15 2014 True
2 23477.0 ACME Industrial 50000.0 62500.0 0.25 125.0 3 29 2016 True
3 24900.0 Brekke LTD 350000.0 490000.0 0.04 75.0 10 27 2015 True
4 651029.0 Harbor Co 15000.0 12750.0 -0.15 NaN 2 2 2014 False

 

 

 

來自:https://github.com/xitu/gold-miner/blob/master/TODO1/pandas-dtypes.md


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM