1. 程式人生 > 實用技巧 >Pandas系列教程(2)Pandas資料結構

Pandas系列教程(2)Pandas資料結構

Pandas資料結構

DataFrame: 二維陣列,整個表格,多行多列

Series: 一維資料,一行或一列

1、Series

Series是一種類似於一維陣列的物件,他由一組資料(不同資料型別)以及一組與之相關的資料標籤(即索引)組成

import pandas as pd
import numpy as np

# ================= 1 僅有資料列表即可產生最簡單的Series =================
s1 = pd.Series([1, 'a', 5.2, 7])
# 左側為索引,右側是資料
print(s1)
# 獲取索引
print(s1.index)
# 獲取資料 print(s1.values) print('*' * 50) # ================= 2 建立一個具有標籤索引的Series ================= s2 = pd.Series([1, 'a', 5.2, 7], index=['d', 'b', 'a', 'c']) # 左側為索引,右側是資料 print(s2) # 獲取索引 print(s2.index) # 獲取資料 print(s2.values) print('*' * 50) # ================= 3 使用Python字典建立Series =================
data = {"Ohio": 35000, "Texas": 72000, "Oregon": 16000, "Utah": 5000} s3 = pd.Series(data) # 左側為索引,右側是資料 print(s3) # 獲取索引 print(s3.index) # 獲取資料 print(s3.values) # ================= 4 根據標籤索引查詢資料 ================= s4 = pd.Series([1, 'a', 5.2, 7], index=['d', 'b', 'a', 'c']) # 左側為索引,右側是資料 print(s4) # 獲取index為a的元素
print(s4['a']) print(type(s4['a'])) # 獲取指定的多個值 print(s4[['b', 'a']]) print(type(s4[['b', 'a']]))

2、DataFrame

DataFrame是一個表格型的資料結構

  • 每列可以是不同的值型別(數值,字串,布林值等)

  • 既有行索引index, 也有columns

  • 可以被看做由Series組成的字典

建立dataframe最常用的方法,見Panda資料讀取

import pandas as pd

data = {
    "state": ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
    "year": [2000, 2001, 2002, 2003, 2004],
    "pop": [1.5, 1.7, 3.6, 2.4, 2.9]
}
df = pd.DataFrame(data)
print(df)

# 獲取每列的資料型別
print(df.dtypes)

# 獲取每列的鍵名
print(df.columns)

# 獲取索引
print(df.index)

3、從DataFrame中查詢出Series

  • 如果只查詢出一行,一列,返回的是pd.Series

  • 如果查詢多列,多行,發揮的是pd.DataFrame

import pandas as pd

data = {
    "state": ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
    "year": [2000, 2001, 2002, 2003, 2004],
    "pop": [1.5, 1.7, 3.6, 2.4, 2.9]
}
df = pd.DataFrame(data)
print(df, '\n')

# 查詢一列,結果是一個pd.Series
print(df['year'], type(df['year']), '\n')

# 查詢多列,結果是一個pd.DataFrame
print(df[['year', 'pop']], type(df[['year', 'pop']]), '\n')

# 查詢一行,結果是一個pd.Series
print(df.loc[1], type(df.loc[1]), '\n')

# 查詢多行,結果是一個pd.DataFrame
print(df.loc[1:3], type(df.loc[1:3]))