Python 資料科學之 Pandas

Galois發表於2020-03-16

生成 Series 資料

用值列表生成 Series 時,Pandas 預設自動生成整數索引:

import numpy as np
import pandas as pd

s = pd.Series([1, 3, 5, np.nan, 6, 8])
s

# Output
0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64

用含日期時間索引與標籤的 NumPy 陣列生成 DataFrame:

dates = pd.date_range('20130101', periods=6)
dates

# Output
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
df

Output:

g8L67dJkXB.png!large

用 Series 字典物件生成 DataFrame:

df2 = pd.DataFrame({'A': 1.,
                    'B': pd.Timestamp('20130102'),
                    'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                    'D': np.array([3] * 4, dtype='int32'),
                    'E': pd.Categorical(["test", "train", "test", "train"]),
                    'F': 'foo'})
df2

Output:

3BTyaQnboC.png!large

DataFrame 的列有不同資料型別:

df2.dtypes

# Output
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object

IPython支援 tab 鍵自動補全列名與公共屬性。下面是部分可自動補全的屬性:

  • df2.A
  • df2.abs
  • df2.add
  • df2.add_prefix
  • df2.add_suffix
  • df2.align
  • df2.all
  • df2.any
  • df2.append
  • df2.apply
  • df2.applymap
  • df2.D
  • df2.bool
  • df2.boxplot
  • df2.C
  • df2.clip
  • df2.clip_lower
  • df2.clip_upper
  • df2.columns
  • df2.combine
  • df2.combine_first
  • df2.compound
  • df2.consolidate

列 A、B、C、D 和 E 都可以自動補全;為簡潔起見,此處只顯示了部分屬性。

檢視資料

# 檢視 DataFrame 頭部資料
df.head()
# 檢視 DataFrame 尾部資料
df.tail(3)
# 顯示索引
df.index
# 顯示列名
df.columns
# 顯示值
df.values
# 快速檢視資料的統計摘要
df.describe()
# 轉制資料
df.T
# 按軸排序
df.sort_index(axis=1, ascending=False)
# 按值排序
df.sort_values(by='B')

獲取資料

選擇

提醒
選擇、設定標準 Python / Numpy 的表示式已經非常直觀,互動也很方便,但對於生產程式碼,我們還是推薦優化過的 Pandas 資料訪問方法:.at.iat.loc.iloc

詳見索引與選擇資料多層索引與高階索引文件。

# 選擇單列,產生 Series,與 `df.A` 等效
df['A']

# Output
2013-01-01   -1.208257
2013-01-02   -1.102261
2013-01-03   -0.059864
2013-01-04    0.644392
2013-01-05   -1.350474
2013-01-06    1.402061
Freq: D, Name: A, dtype: float64

按標籤選擇

# 用標籤提取一行資料
df.loc[dates[0]]

# Output
A   -1.208257
B    2.018486
C    0.679159
D   -0.587707
Name: 2013-01-01 00:00:00, dtype: float64

# 用標籤選擇多列資料
df.loc[:, ['A', 'B']]

Output:

RCRhvI3xvI.png!large

用標籤切片,包含行與列結束點

df.loc['20130102':'20130104', ['A', 'B']]

Output:

jnuLtQhyQB.png!large

# 返回物件降維
df.loc['20130102', ['A', 'B']]

# Output
A   -1.102261
B   -0.538013
Name: 2013-01-02 00:00:00, dtype: float64

# 提取標量值
df.loc[dates[0], 'A']
# Output
-1.2082567185245703

# 快速訪問標量,與 loc 等效
df.at[dates[0], 'A']
# Output
-1.2082567185245703

按位置選擇

用整數位置選擇:

df.iloc[3]
# Output
A    0.644392
B    0.316984
C   -0.583878
D    1.197701
Name: 2013-01-04 00:00:00, dtype: float64

# 類似 NumPy / Python,用整數切片:
df.iloc[3:5, 0:2]

Output:

jbyTpc2Qd2.png!large

# 類似 NumPy / Python,用整數列表按位置切片:
df.iloc[[1, 2, 4], [0, 2]]

Output:

deNdaxNFVZ.png!large

# 顯式整行切片
df.iloc[1:3, :]

Output:

Nb05QkAKX0.png!large

# 顯式整列切片
df.iloc[:, 1:3]

Output:

xwcvYg60G2.png!large

# 顯式提取值
df.iloc[1, 1]
# Output
-0.5380131662468983

# 快速訪問標量 等效與 iloc
df.iat[1, 1]
# Output
-0.5380131662468983

布林索引

# 用單列的值選擇資料
df[df.A > 0]

Output:

JcVK9eOp0u.png!large

# 選擇 DataFrame 裡滿足條件的值
df[df > 0]

Output:

5jiMFbWtUd.png!large

# 用 isin() 篩選
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
df2

Output:

CJHGC7j8Df.png!large

df2[df2['E'].isin(['two', 'four'])]

Output:

ft45HGgwuI.png!large

賦值

用索引自動對齊新增列的資料:

s1 = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range('20130102', periods=6))
s1
# Output
2013-01-02    1
2013-01-03    2
2013-01-04    3
2013-01-05    4
2013-01-06    5
2013-01-07    6
Freq: D, dtype: int64
df['F'] = s1

# 按標籤賦值
df.at[dates[0], 'A'] = 0

# 按位置賦值
df.iat[0, 1] = 0

# 按 NumPy 陣列賦值
df.loc[:, 'D'] = np.array([5] * len(df))

df

Output:

yDjUAIDcqT.png!large

# 用 where 條件賦值
df2 = df.copy()
df2[df2 > 0] = -df2
df2

Output:

GPXS5RHsgK.png!large

缺失值

Pandas 主要用 np.nan 表示缺失資料。 計算時,預設不包含空值。詳見缺失資料

重建索引(reindex)可以更改、新增、刪除指定軸的索引,並返回資料副本,即不更改原資料。

df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]:dates[1], 'E'] = 1
df1

Output:

Qtmaax1jjc.png!large

# 刪除所有含缺失值的行
df1.dropna(how='any')

Output:

Gz8BsFnyO9.png!large

# 填充缺失值
df1.fillna(value=5)

Output:

lemZ9okPNR.png!large

# 提取 nan 值的布林掩碼
pd.isna(df1)

q8ihVuRn5v.png!large

運算

二進位制操作

統計

一般情況下,運算時排除缺失值。
描述性統計:

df.mean()
# Output
A   -0.077691
B    0.049952
C    0.017299
D    5.000000
F    3.000000
dtype: float64

# 在另一個軸(即,行)上執行同樣的操作
df.mean(1)

# Output
2013-01-01    1.419790
2013-01-02    0.650095
2013-01-03    1.482753
2013-01-04    1.675500
2013-01-05    1.271426
2013-01-06    2.771865
Freq: D, dtype: float64

# 不同維度物件運算時,要先對齊。 此外,Pandas 自動沿指定維度廣播
s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
s

# Output
2013-01-01    NaN
2013-01-02    NaN
2013-01-03    1.0
2013-01-04    3.0
2013-01-05    5.0
2013-01-06    NaN
Freq: D, dtype: float64
df.sub(s, axis='index')

ghJIHT5WNs.png!large

Apply 函式

Apply 函式處理資料:

df.apply(np.cumsum)

Output:

0seYJYIl9m.png!large

df.apply(lambda x: x.max() - x.min())
# Output
A    2.752535
B    1.907837
C    2.480673
D    0.000000
F    4.000000
dtype: float64

直方圖

s = pd.Series(np.random.randint(0, 7, size=10))
s
# Output
0    2
1    5
2    1
3    6
4    0
5    0
6    6
7    0
8    6
9    3
dtype: int64

s.value_counts()
# Output
6    3
0    3
5    1
3    1
2    1
1    1
dtype: int64

字串方法

Series 的 str 屬性包含一組字串處理功能,如下列程式碼所示。注意,str 的模式匹配預設使用正規表示式。詳見向量字串方法

s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()

# Output
0       a
1       b
2       c
3    aaba
4    baca
5     NaN
6    caba
7     dog
8     cat
dtype: object

合併(Merge)

結合(Concat)

Pandas 提供了多種將 Series、DataFrame 物件組合在一起的功能,用索引與關聯代數功能的多種設定邏輯可執行連線(join)與合併(merge)操作。
concat() 用於連線 Pandas 物件:

df = pd.DataFrame(np.random.randn(10, 4))
df

Output:

9bwun04Kwv.png!large

# 分解為多組
pieces = [df[:3], df[3:7], df[7:]]
pd.concat(pieces)

Output:

BoAaEWjlvl.png!large

連線(join)

SQL 風格的合併。 詳見資料庫風格連線

left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
left

Output:

y3tGls7CLh.png!large

right

Output:

Se9E58C2Y5.png!large

合併

pd.merge(left, right, on='key')

Output:

rWkY2C5nMJ.png!large

left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
left

Output:

nKRdhLKPIL.png!large

right

Output:

nzKj5fPyiy.png!large

pd.merge(left, right, on='key')

Output:

4kGughhZtq.png!large

追加(Append)

為 DataFrame 追加行。

df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
df

Output:

d9K85QG1PF.png!large

s = df.iloc[3]
df.append(s, ignore_index=True)

Output:

X1jZEdQrQV.png!large

分組(Grouping)

“group by” 指的是涵蓋下列一項或多項步驟的處理流程:

  • 分割:按條件把資料分割成多組;
  • 應用:為每組單獨應用函式;
  • 組合:將處理結果組合成一個資料結構。
    df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
                           'foo', 'bar', 'foo', 'foo'],
                     'B': ['one', 'one', 'two', 'three',
                           'two', 'two', 'one', 'three'],
                     'C': np.random.randn(8),
                     'D': np.random.randn(8)})
    df

Output:

jokSA5WrRO.png!large

# 先分組,再用 sum()函式計算每組的彙總資料
df.groupby('A').sum()

Output:

JlyJMFM3jJ.png!large

多列分組後,生成多層索引,也可以應用 sum 函式:

df.groupby(['A', 'B']).sum()

xg47rAEH3t.png!large

重塑(Reshaping)

詳見多層索引重塑

堆疊(Stack)

tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
                     'foo', 'foo', 'qux', 'qux'],
                    ['one', 'two', 'one', 'two',
                     'one', 'two', 'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
df2 = df[:4]
df2

Output:

cCZEu3qXwj.png!large

stack()方法把 DataFrame 列壓縮至一層:

stacked = df2.stack()
stacked
# Output
first  second
bar    one     A   -0.282081
               B   -1.133788
       two     A   -0.225216
               B   -1.659150
baz    one     A    0.281171
               B   -2.048107
       two     A    0.697422
               B   -1.202862
dtype: float64

壓縮後的 DataFrame 或 Series 具有多層索引, stack() 的逆操作是 unstack(),預設為拆疊最後一層:

stacked.unstack()

Output:

OWN6HYH8fA.png!large

stacked.unstack(1)

Output:

EpeoLck9oA.png!large

stacked.unstack(0)

Output:

tHkJ4RX2qm.png!large

資料透視表(Pivot Tables)

df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 3,
                   'B': ['A', 'B', 'C'] * 4,
                   'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
                   'D': np.random.randn(12),
                   'E': np.random.randn(12)})
df

Output:

7DNWHPSRbm.png!large

用上述資料生成資料透視表非常簡單:

pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])

Output:

Qij7OwKuNE.png!large

時間序列(TimeSeries)

Pandas 為頻率轉換時重取樣提供了雖然簡單易用,但強大高效的功能,如,將秒級的資料轉換為 5 分鐘為頻率的資料。這種操作常見於財務應用程式,但又不僅限於此。

rng = pd.date_range('1/1/2012', periods=100, freq='S')
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts.resample('5Min').sum()

# Output
2012-01-01    27830
Freq: 5T, dtype: int64

# 時區表示
rng = pd.date_range('3/6/2012 00:00', periods=5, freq='D')
ts = pd.Series(np.random.randn(len(rng)), rng)
ts

# Output
2012-03-06   -0.122874
2012-03-07    3.048883
2012-03-08    0.974570
2012-03-09    0.676963
2012-03-10    1.857628
Freq: D, dtype: float64

ts_utc = ts.tz_localize('UTC')
ts_utc

# Output
2012-03-06 00:00:00+00:00   -0.122874
2012-03-07 00:00:00+00:00    3.048883
2012-03-08 00:00:00+00:00    0.974570
2012-03-09 00:00:00+00:00    0.676963
2012-03-10 00:00:00+00:00    1.857628
Freq: D, dtype: float64

# 轉換成其它時區
ts_utc.tz_convert('US/Eastern')

# Output
2012-03-05 19:00:00-05:00   -0.122874
2012-03-06 19:00:00-05:00    3.048883
2012-03-07 19:00:00-05:00    0.974570
2012-03-08 19:00:00-05:00    0.676963
2012-03-09 19:00:00-05:00    1.857628
Freq: D, dtype: float64

# 轉換時間段
rng = pd.date_range('1/1/2012', periods=5, freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts

# Output
2012-01-31   -1.263639
2012-02-29   -0.101891
2012-03-31   -0.578687
2012-04-30   -1.472608
2012-05-31    0.565977
Freq: M, dtype: float64

ps = ts.to_period()
ps

# Output
2012-01   -1.263639
2012-02   -0.101891
2012-03   -0.578687
2012-04   -1.472608
2012-05    0.565977
Freq: M, dtype: float64

ps.to_timestamp()

# Output
2012-01-01   -1.263639
2012-02-01   -0.101891
2012-03-01   -0.578687
2012-04-01   -1.472608
2012-05-01    0.565977
Freq: MS, dtype: float64

Pandas 函式可以很方便地轉換時間段與時間戳。下例把以 11 月為結束年份的季度頻率轉換為下一季度月末上午 9 點:

prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
ts = pd.Series(np.random.randn(len(prng)), prng)
ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
ts.head()

# Output
1990-03-01 09:00   -1.147739
1990-06-01 09:00    1.924324
1990-09-01 09:00   -0.451538
1990-12-01 09:00    0.978331
1991-03-01 09:00   -0.419933
Freq: H, dtype: float64

類別型(Categoricals)

Pandas 的 DataFrame 裡可以包含類別資料。API 文件

df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6],
                   "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']})
# 將 grade 的原生資料轉換為類別型資料
df["grade"] = df["raw_grade"].astype("category")
df["grade"]

# Output
0    a
1    b
2    b
3    a
4    a
5    e
Name: grade, dtype: category
Categories (3, object): [a, b, e]

用有含義的名字重新命名不同型別,呼叫 Series.cat.categories

df["grade"].cat.categories = ["very good", "good", "very bad"]

重新排序各類別,並新增缺失類,Series.cat 的方法預設返回新 Series。

df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium",
                                              "good", "very good"])
df["grade"]

# Output
0    very good
1         good
2         good
3    very good
4    very good
5     very bad
Name: grade, dtype: category
Categories (5, object): [very bad, bad, medium, good, very good]

注意,這裡是按生成類別時的順序排序,不是按詞彙排序:

df.sort_values(by="grade")

Output:

zxoLlqtb9C.png!large

按類列分組(groupby)時,即便某類別為空,也會顯示:

df.groupby("grade").size()

# Output
grade
very bad     1
bad          0
medium       0
good         2
very good    3
dtype: int64

視覺化

ts = pd.Series(np.random.randn(1000),
               index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()

Output:

<matplotlib.axes._subplots.AxesSubplot at 0x11a89e240>

tCs2ikEZl9.png!large

DataFrame 的 plot() 方法可以快速繪製所有帶標籤的列:

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
import matplotlib.pyplot as plt
plt.figure()
df.plot()
plt.legend(loc='best')

Output:

<matplotlib.legend.Legend at 0x11c9dc198>
<Figure size 432x288 with 0 Axes>

lfKZLaDAvp.png!large

資料輸入 / 輸出

CSV

# 寫入 CSV 檔案
df.to_csv('foo.csv')

# 讀取 CSV 檔案資料
pd.read_csv('foo.csv')

HDF5

# 寫入 HDF5 Store
df.to_hdf('foo.h5', 'df')

# 讀取 HDF5 Store
pd.read_hdf('foo.h5', 'df')

Excel

# 寫入 Excel 檔案
df.to_excel('foo.xlsx', sheet_name='Sheet1')

# 讀取 Excel 檔案
pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])

各種坑(Gotchas)

執行某些操作,將觸發異常,如:

>>> if pd.Series([False, True, False]):
...    print("I was true")

Traceback
    ...
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

參閱比較操作文件,檢視錯誤提示與解決方案。詳見各種坑文件。Pandas

本作品採用《CC 協議》,轉載必須註明作者和本文連結

不要試圖用百米衝刺的方法完成馬拉松比賽。

相關文章