Pandas เป็นไลบรารี่ยอดนิยมสำหรับ Data Science และ Analytics ใช้สำหรับ Data Manipulation, Analysis และ Cleaning เป็น High-level Abstraction อยู่เหนือ NumPy ที่เขียนด้วย C เนื้อหานี้ครอบคลุมสิ่งสำคัญที่ Analyst/Data Scientist ควรรู้
ติดตั้งไลบรารี่
pip install pandas matplotlib
DataFrame และ Series
โครงสร้างข้อมูลหลัก 2 แบบของ Pandas
Series
คล้าย List แต่มี Label (Index) ผูกมาด้วยแต่ละ Element
import pandas as pd
my_series = pd.Series([12, 24, 36, 48, 60, 72, 84])
print(my_series)
# กำหนด Index เอง
my_series = pd.Series([12, 24, 36, 48, 60, 72, 84],
index=['ind0', 'ind1', 'ind2', 'ind3', 'ind4', 'ind5', 'ind6'])
print(my_series[['ind0', 'ind3', 'ind6']])
# Filtering และ Math Operations
print(my_series[my_series > 24])
DataFrame
ทำงานเหมือนตาราง มี Rows และ Columns แต่ละ Column เป็น Series
df = pd.DataFrame({
'Country': ['China', 'India', 'Indonesia', 'Pakistan'],
'Population': [1420062022, 1368737513, 269536482, 204596442],
'Area': [9388211, 2973190, 1811570, 770880]
}, index=['CHA', 'IND', 'IDO', 'PAK'])
print(df)
print(df.loc['IND'])
print(df.iloc[1])
อ่าน/เขียนไฟล์
รองรับ CSV, Excel, JSON, SQL, HTML, XML ฯลฯ
# อ่าน CSV
df = pd.read_csv('data.csv', sep=',')
# เขียน CSV
df.to_csv('output.csv', index=False)
Aggregating และ Grouping
# Titanic Dataset Example
titanic_df = pd.read_csv('titanic.csv')
# จำนวนผู้รอดชีวิต แยกเพศ
print(titanic_df.groupby(['Sex', 'Survived'])['PassengerID'].count())
# จำนวนผู้รอดชีวิต แยก Class
print(titanic_df.groupby(['PClass', 'Survived'])['PassengerID'].count())
Time Series Analysis
amzn_df = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True)
amzn_df = amzn_df.sort_index()
print(amzn_df.loc['2015-04', 'Close'].mean())
Visualization ด้วย Matplotlib
import matplotlib.pyplot as plt
df = pd.read_csv('AMZN.csv', index_col='Date', parse_dates=True)
new_df = df.loc['2014-06':'2018-08', ['Close']].astype(float)
new_df.plot()
plt.title('Amazon Stock Price')
plt.show()
