> For the complete documentation index, see [llms.txt](https://brianwu.gitbook.io/brian/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://brianwu.gitbook.io/brian/python/pandas.md).

# Pandas

參考資料:(<https://oranwind.org/python-pandas-ji-chu-jiao-xue/>) 參考資料:(<https://srdatw.blogspot.com/2019/01/python-pandas.html>)

Python 的一種數據分析 lib 提供主要兩種資料結構 DataFrame & Series 透過載入至資料結構物件後，可以使用物件提供的方法，來快速進行前處理(資料補值、空值去除、取代) 更多的輸入、輸出整合，EX：從DB讀取資料，將處理完的資料倒回DB

## 資料結構

### Series

用來處理時間序列相關的資料 (如感測器資料) 主要為建立索引的一維陣列

### DataFrame

則是用來處理結構化 (Table like) 的資料 有 **列索引** 與 **欄標籤** 的二維資料 例如：關聯式資料庫、CSV

### Panel

用來處理有資料、索引、列索引、欄標籤 的三維資料集。

## 讀取檔案

### CSV

```
import pandas as pd #引用套件並縮寫為 pd
df = pd.read_csv('fileName.csv')
print(df)
```

### Html

```
import pandas as pd
dfs = pd.read_html('url')
dfs[0]
```

## 方法

### 排序

`.sort_index()` `.sort_values()`

### 判斷是否為空

`isnull()` `notnull()` `isna()`

### 檢查特定值

`isin(value)`

### 處理空值

`dropna() #有 null 都刪除`

`fillna(0) #有null 都補0` `fillna({'key': "NULL", "key2": 0}) #依照欄位補值`

### 檢查重複值

`df.duplicated('columnName')`

### 檢查區間值

`.between(value1,value2)`

### 修改值

`df.loc[index, column] = value`

### 修改 columnName

`df.rename(columns = {column : cloumn_modify})`

### 用 replace() 重新編碼

1 和 2 改為 1，3 和 4 改為 2 `df[column].replace({1:1, 2:1, 3:2, 4:2}, inplace=True) #inplace=True 才會寫入`

## 畫圖

參考資料:(<https://amaozhao.gitbooks.io/pandas-notebook/content/pandas%E4%B8%AD%E7%9A%84%E7%BB%98%E5%9B%BE%E5%87%BD%E6%95%B0.html>)

### 折線圖

```
s = Series(np.random.randn(10).cumsum(), index = np.arange(0, 100, 10))
s.plot()
```

## DataFrame 的操作

### .shape

return 列數、欄數

### .describe()

return 描述性統計

count 筆數 mean 平均數 std 標準差 min 最小值 25% 各四分位數 50% 75% max 最大值

### .head()

return 前五筆 (可代入 n，則回傳 n 筆)

### .tail()

return 後五筆 (同上)

### .columns

return 欄位名稱

### .index

return index

### info()

return 資料內容
