上一次我分享了 Numpy 的學習心得,沒看過的朋友點這里 numpy
這次我們學習另一個非常重要的工具 Pandas,很多小伙伴可能已經(jīng)聽說過 pandas 了,pandas 是基于 numpy 構(gòu)建的含有更高級數(shù)據(jù)結(jié)構(gòu)和分析能力的工具包,功能更強大,我們趁熱打鐵,在學完上面的 Numpy 后把 pandas 學到手。
pandas 有兩種數(shù)據(jù)結(jié)構(gòu):Series 和 DataFrme
Series 是個定長的字典序列,在存儲的時候相當于兩個 ndarray。Series有兩個基本屬性:index 和 values, index 默認是 0, 1, 2.....,我們也可以自己指定比如:index = ['a', 'b', 'c', 'd']
import pandas as pd
from pandas import Series, DataFrame
a = Series([1, 2, 3, 4])
c = Series(data=(1, 2, 3, 4), index=['a', 'b', 'c', 'd'])
print(a)
print(c)
輸出結(jié)果
0 1
1 2
2 3
3 4
dtype: int64
a 1
b 2
c 3
d 4
dtype: int64
我們也可以像創(chuàng)建字典一樣創(chuàng)建 Series
f = {'a':1, 'b': 2, 'c': 3}
x1 = Series(f)
print(x1)
a 1
b 2
c 3
dtype: int64
DataFrame 包含了行索引和列索引,類似于數(shù)據(jù)庫表。
期末了,我們虛構(gòu)幾個同學考試的場景,輸出考試成績。
import pandas as pd
from pandas import Series, DataFrame
data = {'Chinese': [68, 88, 78, 98], 'Math': [14, 67, 88, 65],
'English': [100, 55, 87, 98]}
df1 = DataFrame(data)
df2 = DataFrame(data, index=['Zhangsan', 'Lisi', 'Wangwu', 'Zhaoliu'])
print(df1)
print(df2)
output
Chinese Math English
0 68 14 100
1 88 67 55
2 78 88 87
3 98 65 98
Chinese Math English
Zhangsan 68 14 100
Lisi 88 67 55
Wangwu 78 88 87
Zhaoliu 98 65 98
df2 中,行索引是 ['Zhangsan', 'Lisi', 'Wangwu', 'Zhaoliu'],列索引是 ['Chinese', 'Math', 'English']。
數(shù)據(jù)清洗
數(shù)據(jù)清洗是數(shù)據(jù)處理過程中必不可少的環(huán)節(jié),Pandas 為我們提供了許多工具,這里我簡單介紹下 Pandas 數(shù)據(jù)清洗的工具。
以上面考試做例子。
data = {'Chinese': [68, 88, 78, 98], 'Math': [14, 67, 88, 65],
'English': [100, 55, 87, 98]}
df = DataFrame(data, index=['Zhangsan', 'Lisi', 'Wangwu', 'Zhaoliu'],
columns=['English', 'Math', 'Chinese'])
print(df)
English Math Chinese
Zhangsan 100 14 68
Lisi 55 67 88
Wangwu 87 88 78
Zhaoliu 98 65 98
1. 刪除某行或某列
比如把 '語文' 這列刪掉。把 " Zhangsan " 這行刪掉
df = df.drop(columns=['Chinese'])
df = df.drop(index=['Zhangsan'])
重命名列名 columns
df.rename(columns={'Chinese': '語文'}, inplace=True)
去除重復的值
df = df.drop_duplicates()
格式問題
# 更改數(shù)據(jù)格式
df["Chinese"].astype('str')
df["Chinese"].astype(np.int64)
# 刪除數(shù)據(jù)間的空格
df['Chinese'] = df2['Chinese'].map(str.strip) # 刪除左右兩邊空格
df['Chinese'] = df2['Chinese'].map(str.lstrip) # 刪除左邊空格
df['Chinese'] = df2['Chinese'].map(str.rstrip) # 刪除右邊空格
df['Chinese'] = df2['Chinese'].str.strip('$')
# 去除特殊符號
大小寫轉(zhuǎn)換
# 全部大寫
df.columns = df.columns.str.upper()
# 全部小寫
df.columns = df.columns.str.lower()
# 首字母大寫
df.columns = df.columns.str.title()
查找空值
有些字段可能存在空值,我們需要用 pandas 的 isnull 函數(shù)進行查找。
比如下面這個數(shù)據(jù)表
English Math Chinese
Zhangsan 100 NaN 68
Lisi 55 67.0 88
Wangwu 87 88.0 78
Zhaoliu 98 65.0 98
我們用 df.isnull() 查看哪里出現(xiàn)空值,用 df.isnull().any() 查看那一列出現(xiàn)空值。
print(df.isnull())
English Math Chinese
Zhangsan False True False
Lisi False False False
Wangwu False False False
Zhaoliu False False False
可以看到第一行第二列出現(xiàn)空值
print(df.isnull().any())
English False
Math True
Chinese False
dtype: bool
數(shù)學這一列出現(xiàn)空值
使用 apply 函數(shù)進行清洗
比如對 name 列的數(shù)值進行大寫轉(zhuǎn)化
df['name'] = df['name'].apply(str.upper)
比如對某一列的數(shù)值 * 3 倍返回。
def triple_df(x):
return 3 *x
df['Chinese'] = df['Chinese'].apply(triple_df)
print(df)
English Math Chinese
Zhangsan 100 78 204
Lisi 55 67 264
Wangwu 87 88 234
Zhaoliu 98 65 294
定義更復雜的函數(shù),我們新增兩列,其中 'new1' 是 " Chinese " 和 " Math " 之和的 m 倍, 'new2' 是 " Chinese " 和 " Math " 之和的 n 倍。
def plus(df, n, m):
df['new1'] = (df['Chinese'] + df['Math']) * m
df['new2'] = (df['Chinese'] + df['Math']) * n
return df
df = df.apply(plus, axis=1, args=(2, 3))
print(df)
English Math Chinese new1 new2
Zhangsan 100 78 68 438 292
Lisi 55 67 88 465 310
Wangwu 87 88 78 498 332
Zhaoliu 98 65 98 489 326
數(shù)據(jù)統(tǒng)計
我們直接用 describe() 函數(shù),可以對數(shù)據(jù)進行全面的了解。
print(df.describe())
English Math Chinese
count 4.000000 4.000000 4.000000
mean 85.000000 74.500000 83.000000
std 20.800641 10.661457 12.909944
min 55.000000 65.000000 68.000000
25% 79.000000 66.500000 75.500000
50% 92.500000 72.500000 83.000000
75% 98.500000 80.500000 90.500000
max 100.000000 88.000000 98.000000
練習題
學了后一定要練習,練習,練習,你才能夠成長。
對于下表數(shù)據(jù),請使用 Pandas 中的 DataFrame 進行創(chuàng)建,并對數(shù)據(jù)進行清洗。同時新加一列求每個人的三科成績。(盡可能用到所有知識)
在評論區(qū)與我分享你的答案。