iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
AI & Data

使用python學習Machine Learning系列 第 13

Day 13 [Python ML、Pandas] 創建、讀取和寫入

Introduction

在這個課程裡,會學到最熱門的資料分析套件,pandas

Getting Start

import 套件

import pandas as pd

Creating Data

DataFrame

使用DataFrame產生類似table的資料結構

pd.DataFrame({'Yes': [50, 21], 'No': [131, 2]})
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

資料不一定要是數值屬性

pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'], 'Sue': ['Pretty good.', 'Bland.']})
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

可以利用 index參數 來改變index的資料

pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'], 
              'Sue': ['Pretty good.', 'Bland.']},
             index=['Product A', 'Product B'])
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

Series

可以利用Series產生類似於list的資料結構

pd.Series([1, 2, 3, 4, 5])
0    1
1    2
2    3
3    4
4    5
dtype: int64

Series可以算是一個單column的DataFrame

因此也可以對index做調整

也因為只有單行 可以利用 name參數 改變Series的資料

pd.Series([30, 35, 40], index=['2015 Sales', '2016 Sales', '2017 Sales'], name='Product A')
2015 Sales    30
2016 Sales    35
2017 Sales    40
Name: Product A, dtype: int64

Reading data files

pandas也可以讀取csv檔案,使用.read_csv函數

wine_reviews = pd.read_csv('./winemag-data-130k-v2.csv')
wine_reviews.shape
(129971, 14)

可以利用shape來看pandas的行列(column, row)資料有多少

wine_reviews.head()
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

head()可以印出資料中的前5筆資料

因為.read_csv可以取得全部的資料,因此也會將index取進來

可以使用index_col=0來去掉index的column

wine_reviews = pd.read_csv('./winemag-data-130k-v2.csv', index_col=0)
wine_reviews.head()
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

另外.to_csv可以將dataframe轉為csv檔匯出

animals = pd.DataFrame({'Cows': [12, 20], 'Goats': [22, 19]}, index=['Year 1', 'Year 2'])

# Your code goes here
animals.to_csv('cows_and_goats.csv')

上一篇
Day 12 [Python ML、特徵工程] 特徵工程整理
下一篇
Day 14 [Python ML、Pandas] 引索、選擇和給值
系列文
使用python學習Machine Learning29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言