pandas學習
numpy能夠幫助我們處理數值,但是pandas除了處理數值之外(基於numpy),還能能幫助我們處理其他類型的數據。
常用數據類型有:
- Series一維,帶標籤(索引)數組
- DataFrame二維,Series容器
pandas之Series創建
-
import pandas as pd t1 = pd.Series([1, 2, 31, 12, 3, 4]) print(t1) print(type(t1))
-
可以指定索引創建Series
-
t2 = pd.Series([1, 23, 2, 2, 1], index=list("abcde")) print(t2)
-
可以傳入字典創建Series
-
temp_dict = {"name": "xiaoming", "age": 30, "tel": 10086} t1 = pd.Series(temp_dict) print(t1)
pandas之Series切片和索引
temp_dict = {"name": "xiaoming", "age": 30, "tel": 10086}
t1 = pd.Series(temp_dict)
print(t1["name"])
print(t1[["age", "tel"]])
print(t1.index)
# print(t1[t1>4])
print(t1.values)
print(np.ndarray)
Series對象本質上由兩個數組構成
一個數組構成對象的鍵(index,索引),一個數組構成對象的值(values),鍵->值
ndarray的很多方法都可以運用series類型,比如argmax,clip
Series具有where方法,但是結果和ndarray不同。
pandas之讀取外部數據
df = pd.read_csv("./data")
print(df)
pandas之DataFrame
import pandas as pd
import numpy as np
t1 = pd.DataFrame(np.arange(12).reshape(3, 4))
print(t1)
DataFrame對象既有行索引,又有列索引。
設置索引創建DataFrame對象:
t2 = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz"))
print(t2)
傳入字典創建DataFrame對象:
d1 = {"name": ["xiaoming", "xiaohong"], "age": [20, 32], "tel": [10086, 10010]}
t3 = pd.DataFrame(d1)
print(t3)
d1 = [{"name": "xiaoming", "age": 20, "tel": 10010}, {"name": "xiaohong", "age": 23, "tel": 10086}]
print(d1)
t4 = pd.DataFrame(d1)
print(t4)
基本屬性:
d1 = [{"name": "xiaoming", "age": 20, "tel": 10010}, {"name": "xiaohong", "age": 23, "tel": 10086}]
t4 = pd.DataFrame(d1)
print(t4.index) # 行索引
print(t4.columns) # 列索引
print(t4.values) # 對象值
print(t4.shape) # 行數和列數
print(t4.dtypes) # 元素類型
print(t4.ndim) # 維度
DataFrame整體情況查詢
t4.head(3) # 顯示頭部幾行,默認5行
t4.tail(3) # 顯示末尾幾行,默認5行
t4.info() # 相關信息概覽:行數,列數,列索引,列非空值個數,列類型,內存佔用
t4.describe() # 快速綜合統計結果:計數,均值,標準差,最大值,四分位數,最小值
DataFrame對象的切片
# 方括號裏寫數字,表示取行
print(t4[:1])
# 方括號裏寫字符串,表示取列
print(t4["name"])
# 取某行某列
print(t4[:1]["name"])
pandas之loc
還有更多的經過pandas優化過的選擇方式
- df.loc通過標籤索引行數據
- df.iloc通過位置獲取行數據
t5 = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz"))
print(t5)
a = t5.loc["a", "z"]
print(a)
print(t5.loc["a"])
pandas之布爾索引
print(t5[t5["z"] > 4])
print(t5[t5["row_name"].str.len() > 4])
不同條件之間需要用括號括起來,同時用&,|諸如此類的符號連接。
對電影數據進行處理:
import pandas as pd
from matplotlib import pyplot as plt
file_path = "./IMDB-Movie-Data.csv"
df = pd.read_csv(file_path)
print(df.head(1))
print(df.info())
runtime_data = df["Runtime (Minutes)"].values
max_runtime = runtime_data.max()
min_runtime = runtime_data.min()
# 計算組數
num_bin = (max_runtime - min_runtime) // 5
# 設置圖形的大小
plt.figure(figsize=(20, 8), dpi=80)
# 繪製
plt.hist(runtime_data, num_bin)
# 設置座標軸的刻度
plt.xticks(range(min_runtime, max_runtime + 5, 5))
# 展示
plt.show()