Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 25 — Pandas

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียน Pandas — ไลบรารีสำหรับ data manipulation ที่ทรงพลังที่สุดใน Python ecosystem

30 Days of Python Banner

Pandas

Pandas เป็น open source library ที่มีประสิทธิภาพสูง ใช้งานง่าย สำหรับโครงสร้างข้อมูลและเครื่องมือวิเคราะห์ข้อมูลใน Python Pandas เพิ่มโครงสร้างข้อมูลและเครื่องมือที่ออกแบบมาเพื่อทำงานกับข้อมูลแบบตาราง ได้แก่ Series และ Data Frames Pandas มีเครื่องมือสำหรับการจัดการข้อมูล:

  • reshaping
  • merging
  • sorting
  • slicing
  • aggregation
  • imputation

ถ้าคุณใช้ anaconda อยู่แล้ว ไม่จำเป็นต้องติดตั้ง pandas เพิ่มเติม

การติดตั้ง Pandas

สำหรับ Mac:

python
pip install conda
conda install pandas

สำหรับ Windows:

python
pip install conda
pip install pandas

โครงสร้างข้อมูลของ Pandas อิงจาก Series และ DataFrames

Series คือ column และ DataFrame คือตาราง multidimensional ที่ประกอบด้วย Series หลายชุด ในการสร้าง pandas series เราควรใช้ numpy เพื่อสร้าง array หนึ่งมิติ หรือใช้ python list มาดูตัวอย่างของ series:

Names Pandas Series

pandas series
ตัวอย่าง Names Pandas Series

Countries Series

pandas series
ตัวอย่าง Countries Series

Cities Series

pandas series
ตัวอย่าง Cities Series

ดังที่เห็น pandas series คือข้อมูลเพียงหนึ่งคอลัมน์ ถ้าต้องการหลายคอลัมน์ เราใช้ data frames ตัวอย่างด้านล่างแสดง pandas DataFrames

มาดูตัวอย่าง pandas data frame:

Pandas data frame
ตัวอย่าง Pandas DataFrame

Data frame คือชุดของแถวและคอลัมน์ ดูตารางด้านล่าง มีคอลัมน์มากกว่าตัวอย่างข้างบนมาก:

Pandas data frame
ตัวอย่าง Pandas DataFrame ที่มีหลายคอลัมน์

ต่อไป เราจะดูวิธี import pandas และวิธีสร้าง Series และ DataFrames โดยใช้ pandas

การ Import Pandas

python
import pandas as pd # importing pandas as pd
import numpy  as np # importing numpy as np

การสร้าง Pandas Series ด้วย Default Index

python
nums = [1, 2, 3, 4,5]
s = pd.Series(nums)
print(s)
shell
    0    1
    1    2
    2    3
    3    4
    4    5
    dtype: int64

การสร้าง Pandas Series ด้วย Index ที่กำหนดเอง

python
nums = [1, 2, 3, 4, 5]
s = pd.Series(nums, index=[1, 2, 3, 4, 5])
print(s)
shell
    1    1
    2    2
    3    3
    4    4
    5    5
    dtype: int64
python
fruits = ['Orange','Banana','Mango']
fruits = pd.Series(fruits, index=[1, 2, 3])
print(fruits)
shell
    1    Orange
    2    Banana
    3    Mango
    dtype: object

การสร้าง Pandas Series จาก Dictionary

python
dct = {'name':'Asabeneh','country':'Finland','city':'Helsinki'}
python
s = pd.Series(dct)
print(s)
shell
    name       Asabeneh
    country     Finland
    city       Helsinki
    dtype: object

การสร้าง Pandas Series แบบค่าคงที่

python
s = pd.Series(10, index = [1, 2, 3])
print(s)
shell
    1    10
    2    10
    3    10
    dtype: int64

การสร้าง Pandas Series โดยใช้ Linspace

python
s = pd.Series(np.linspace(5, 20, 10)) # linspace(starting, end, items)
print(s)
shell
    0     5.000000
    1     6.666667
    2     8.333333
    3    10.000000
    4    11.666667
    5    13.333333
    6    15.000000
    7    16.666667
    8    18.333333
    9    20.000000
    dtype: float64

DataFrames

Pandas data frames สามารถสร้างได้หลายวิธี

การสร้าง DataFrames จาก List of Lists

python
data = [
    ['Asabeneh', 'Finland', 'Helsink'],
    ['David', 'UK', 'London'],
    ['John', 'Sweden', 'Stockholm']
]
df = pd.DataFrame(data, columns=['Names','Country','City'])
print(df)
NamesCountryCity
0AsabenehFinlandHelsink
1DavidUKLondon
2JohnSwedenStockholm

การสร้าง DataFrame โดยใช้ Dictionary

python
data = {'Name': ['Asabeneh', 'David', 'John'], 'Country':[
    'Finland', 'UK', 'Sweden'], 'City': ['Helsiki', 'London', 'Stockholm']}
df = pd.DataFrame(data)
print(df)
NameCountryCity
0AsabenehFinlandHelsiki
1DavidUKLondon
2JohnSwedenStockholm

การสร้าง DataFrames จาก List ของ Dictionaries

python
data = [
    {'Name': 'Asabeneh', 'Country': 'Finland', 'City': 'Helsinki'},
    {'Name': 'David', 'Country': 'UK', 'City': 'London'},
    {'Name': 'John', 'Country': 'Sweden', 'City': 'Stockholm'}]
df = pd.DataFrame(data)
print(df)
NameCountryCity
0AsabenehFinlandHelsinki
1DavidUKLondon
2JohnSwedenStockholm

การอ่านไฟล์ CSV โดยใช้ Pandas

ในการดาวน์โหลดไฟล์ CSV ที่ใช้ในตัวอย่างนี้ ใช้ console/command line:

shell
curl -O https://raw.githubusercontent.com/Asabeneh/30-Days-Of-Python/master/data/weight-height.csv

วางไฟล์ที่ดาวน์โหลดไว้ใน working directory ของคุณ

python
import pandas as pd

df = pd.read_csv('weight-height.csv')
print(df)

การสำรวจข้อมูล

มาอ่านแค่ 5 แถวแรกโดยใช้ head()

python
print(df.head()) # give five rows we can increase the number of rows by passing argument to the head() method
GenderHeightWeight
0Male73.847017241.893563
1Male68.781904162.310473
2Male74.110105212.740856
3Male71.730978220.042470
4Male69.881796206.349801

มาสำรวจบันทึกท้ายสุดของ dataframe โดยใช้ method tail() ด้วย

python
print(df.tail()) # tails give the last five rows, we can increase the rows by passing argument to tail method
GenderHeightWeight
9995Female66.172652136.777454
9996Female67.067155170.867906
9997Female63.867992128.475319
9998Female69.034243163.852461
9999Female61.944246113.649103

ดังที่เห็น ไฟล์ csv มีสามคอลัมน์ ได้แก่ Gender, Height และ Weight ถ้า DataFrame มีคอลัมน์มาก อาจรู้คอลัมน์ทั้งหมดได้ยาก ดังนั้นเราควรใช้ method เพื่อดูชื่อคอลัมน์ทั้งหมด เราไม่รู้จำนวนแถว มาใช้ method shape กัน

python
print(df.shape) # as you can see 10000 rows and three columns
shell
    (10000, 3)

มาดูคอลัมน์ทั้งหมดโดยใช้ columns

python
print(df.columns)
shell
    Index(['Gender', 'Height', 'Weight'], dtype='object')

ตอนนี้ มาดึงคอลัมน์เฉพาะโดยใช้ key ของคอลัมน์

python
heights = df['Height'] # this is now a series
python
print(heights)
shell
    0       73.847017
    1       68.781904
    2       74.110105
    3       71.730978
    4       69.881796
              ...
    9995    66.172652
    9996    67.067155
    9997    63.867992
    9998    69.034243
    9999    61.944246
    Name: Height, Length: 10000, dtype: float64
python
weights = df['Weight'] # this is now a series
python
print(weights)
shell
    0       241.893563
    1       162.310473
    2       212.740856
    3       220.042470
    4       206.349801
               ...
    9995    136.777454
    9996    170.867906
    9997    128.475319
    9998    163.852461
    9999    113.649103
    Name: Weight, Length: 10000, dtype: float64
python
print(len(heights) == len(weights))
shell
    True

method describe() ให้ค่าสถิติเชิงพรรณนาของ dataset

python
print(heights.describe()) # give statistical information about height data
shell
    count    10000.000000
    mean        66.367560
    std          3.847528
    min         54.263133
    25%         63.505620
    50%         66.318070
    75%         69.174262
    max         78.998742
    Name: Height, dtype: float64
python
print(weights.describe())
shell
    count    10000.000000
    mean       161.440357
    std         32.108439
    min         64.700127
    25%        135.818051
    50%        161.212928
    75%        187.169525
    max        269.989699
    Name: Weight, dtype: float64
python
print(df.describe())  # describe can also give statistical information from a dataFrame
HeightWeight
count10000.00000010000.000000
mean66.367560161.440357
std3.84752832.108439
min54.26313364.700127
25%63.505620135.818051
50%66.318070161.212928
75%69.174262187.169525
max78.998742269.989699

คล้ายกับ describe() method info() ก็ให้ข้อมูลเกี่ยวกับ dataset เช่นกัน

การแก้ไข DataFrame

การแก้ไข DataFrame:

  • เราสามารถสร้าง DataFrame ใหม่ได้
  • เราสามารถสร้างคอลัมน์ใหม่แล้วเพิ่มลงใน DataFrame
  • เราสามารถลบคอลัมน์ที่มีอยู่ออกจาก DataFrame
  • เราสามารถแก้ไขคอลัมน์ที่มีอยู่ใน DataFrame
  • เราสามารถเปลี่ยน data type ของค่าในคอลัมน์ใน DataFrame ได้

การสร้าง DataFrame

เสมอ เราต้อง import package ที่จำเป็นก่อน ตอนนี้ มา import pandas และ numpy สองเพื่อนซี้กัน

python
import pandas as pd
import numpy as np
data = [
    {"Name": "Asabeneh", "Country":"Finland","City":"Helsinki"},
    {"Name": "David", "Country":"UK","City":"London"},
    {"Name": "John", "Country":"Sweden","City":"Stockholm"}]
df = pd.DataFrame(data)
print(df)
NameCountryCity
0AsabenehFinlandHelsinki
1DavidUKLondon
2JohnSwedenStockholm

การเพิ่มคอลัมน์ใน DataFrame ก็เหมือนการเพิ่ม key ใน dictionary

ก่อนอื่น มาใช้ตัวอย่างก่อนหน้านี้เพื่อสร้าง DataFrame หลังจากที่สร้าง DataFrame แล้ว เราจะเริ่มแก้ไขคอลัมน์และค่าในคอลัมน์

การเพิ่มคอลัมน์ใหม่

มาเพิ่มคอลัมน์ weight ใน DataFrame

python
weights = [74, 78, 69]
df['Weight'] = weights
df
NameCountryCityWeight
0AsabenehFinlandHelsinki74
1DavidUKLondon78
2JohnSwedenStockholm69

มาเพิ่มคอลัมน์ height ใน DataFrame ด้วย

python
heights = [173, 175, 169]
df['Height'] = heights
print(df)
NameCountryCityWeightHeight
0AsabenehFinlandHelsinki74173
1DavidUKLondon78175
2JohnSwedenStockholm69169

ดังที่เห็นใน DataFrame ด้านบน เราได้เพิ่มคอลัมน์ใหม่ Weight และ Height แล้ว มาเพิ่มคอลัมน์เพิ่มเติมชื่อ BMI (Body Mass Index) โดยคำนวณจากมวลและส่วนสูง BMI คือมวลหารด้วยส่วนสูงยกกำลังสอง (เป็นเมตร) — Weight/Height * Height

ดังที่เห็น ส่วนสูงอยู่ในหน่วยเซนติเมตร เราจึงต้องเปลี่ยนเป็นเมตร มาแก้ไขแถว height กัน

การแก้ไขค่าในคอลัมน์

python
df['Height'] = df['Height'] * 0.01
df
NameCountryCityWeightHeight
0AsabenehFinlandHelsinki741.73
1DavidUKLondon781.75
2JohnSwedenStockholm691.69
python
# Using functions makes our code clean, but you can calculate the bmi without one
def calculate_bmi ():
    weights = df['Weight']
    heights = df['Height']
    bmi = []
    for w,h in zip(weights, heights):
        b = w/(h*h)
        bmi.append(b)
    return bmi

bmi = calculate_bmi()
python
df['BMI'] = bmi
df
NameCountryCityWeightHeightBMI
0AsabenehFinlandHelsinki741.7324.725183
1DavidUKLondon781.7525.469388
2JohnSwedenStockholm691.6924.158818

การจัดรูปแบบคอลัมน์ใน DataFrame

ค่า BMI ใน DataFrame เป็น float ที่มีทศนิยมหลายตำแหน่ง มาเปลี่ยนให้เหลือทศนิยมหนึ่งตำแหน่ง

python
df['BMI'] = round(df['BMI'], 1)
print(df)
NameCountryCityWeightHeightBMI
0AsabenehFinlandHelsinki741.7324.7
1DavidUKLondon781.7525.5
2JohnSwedenStockholm691.6924.2

ข้อมูลใน DataFrame ยังไม่สมบูรณ์ มาเพิ่มคอลัมน์ปีเกิดและปีปัจจุบัน

python
birth_year = ['1769', '1985', '1990']
current_year = pd.Series(2020, index=[0, 1,2])
df['Birth Year'] = birth_year
df['Current Year'] = current_year
df
NameCountryCityWeightHeightBMIBirth YearCurrent Year
0AsabenehFinlandHelsinki741.7324.717692020
1DavidUKLondon781.7525.519852020
2JohnSwedenStockholm691.6924.219902020

การตรวจสอบ Data Type ของค่าในคอลัมน์

python
print(df.Weight.dtype)
shell
    dtype('int64')
python
df['Birth Year'].dtype # it gives string object , we should change this to number
python
df['Birth Year'] = df['Birth Year'].astype('int')
print(df['Birth Year'].dtype) # let's check the data type now
shell
    dtype('int32')

ตอนนี้ทำเช่นเดียวกันสำหรับ current year:

python
df['Current Year'] = df['Current Year'].astype('int')
df['Current Year'].dtype
shell
    dtype('int32')

ตอนนี้ค่าในคอลัมน์ปีเกิดและปีปัจจุบันเป็น integer แล้ว เราสามารถคำนวณอายุได้

python
ages = df['Current Year'] - df['Birth Year']
ages
shell
    0    251
    1     35
    2     30
    dtype: int32
python
df['Ages'] = ages
print(df)
NameCountryCityWeightHeightBMIBirth YearCurrent YearAges
0AsabenehFinlandHelsinki741.7324.717692019250
1DavidUKLondon781.7525.51985201934
2JohnSwedenStockholm691.6924.21990201929

บุคคลในแถวแรกมีอายุถึง 251 ปี ซึ่งเป็นไปได้ยากมากที่ใครจะมีชีวิตอยู่ได้นานขนาดนั้น อาจเป็นการพิมพ์ผิดหรือข้อมูลถูกสร้างขึ้น ดังนั้นมาใส่ค่าเฉลี่ยของคอลัมน์โดยไม่รวม outlier

mean = (35 + 30)/ 2

python
mean = (35 + 30)/ 2
print('Mean: ',mean)	#it is good to add some description to the output, so we know what is what
shell
   Mean:  32.5

Boolean Indexing

python
print(df[df['Ages'] > 120])
NameCountryCityWeightHeightBMIBirth YearCurrent YearAges
0AsabenehFinlandHelsinki741.7324.717692020251
python
print(df[df['Ages'] < 120])
NameCountryCityWeightHeightBMIBirth YearCurrent YearAges
1DavidUKLondon781.7525.51985202035
2JohnSwedenStockholm691.6924.21990202030

แบบฝึกหัด: วันที่ 25

  1. อ่านไฟล์ hacker_news.csv จาก data directory
  2. ดึง 5 แถวแรก
  3. ดึง 5 แถวท้าย
  4. ดึงคอลัมน์ title เป็น pandas series
  5. นับจำนวนแถวและคอลัมน์
  6. กรอง title ที่มีคำว่า python