Python學(xué)習(xí)筆記(8):Series及DataFrame的索引

書里介紹索引方法以羅列為主,看完容易記住難,并沒有把幾種索引方法總結(jié)歸納出來。所以本篇學(xué)習(xí)筆記,我爭取把幾種索引方法總結(jié)出來,便于記憶。
目錄

  • 一、Series對象索引
    • 1、['索引名'] or ['索引名1' : '索引名2'] or [['索引名1', ..., '索引名n']]
    • 2、[整數(shù)] or [整數(shù)1:整數(shù)2] or [[整數(shù)1,..., 整數(shù)n]]
    • 3、[布爾表達式]
  • 二、DataFrame對象索引
    • 1、['列名1'] or ['列名1',..., '列名n']
    • 2、[整數(shù)1:整數(shù)2]
    • 3、[布爾表達式]
    • 4、ix方法:DataFrame.ix['列名', ['索引名1',..., '索引名n']]

一、Series對象索引

1、['索引名'] or ['索引名1' : '索引名2'] or [['索引名1', ..., '索引名n']]

注:['索引名1' : '索引名2']取出的數(shù)組是左右都包含的。

import pandas as pd
import numpy as np
from pandas import Series, DataFrame
obj = Series(np.arange(4.), index = ['a', 'b', 'c', 'd'])
obj['a']
輸出:0.0

obj['a':'c']
輸出:
a    0.0
b    1.0
c    2.0
dtype: float64

obj[['a', 'b', 'c']]
輸出:
a    0.0
b    1.0
c    2.0
dtype: float64

2、[整數(shù)] or [整數(shù)1:整數(shù)2] or [[整數(shù)1,..., 整數(shù)n]]

[整數(shù)1:整數(shù)2]取出的數(shù)組是包含整數(shù)1不包括整數(shù)2的。

obj[1]
輸出:1.0

obj[1:3]
輸出:
b    1.0
c    2.0
dtype: float64

obj[[0, 2]]
輸出:
a    0.0
c    2.0
dtype: float64

3、[布爾表達式]

obj[obj<2]
輸出:
a    0.0
b    1.0
dtype: float64

二、DataFrame對象索引

DataFrame對象與Series對象索引的區(qū)別在于,在index(索引名)基礎(chǔ)上還有columns(列名)。

1、['列名1'] or [['列名1',..., '列名n']]

data = DataFrame(np.arange(16).reshape((4, 4)), index = ['Ohio', 'Colorado', 'Utah', 'New York'], columns = ['one', 'two', 'three', 'four'])
data
輸出:
    one two three   four
Ohio    0   1   2   3
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15

data['one']
輸出:
Ohio         0
Colorado     4
Utah         8
New York    12
Name: one, dtype: int64

data[['one', 'three']]
輸出:
    one three
Ohio    0   2
Colorado    4   6
Utah    8   10
New York    12  14

2、[整數(shù)1:整數(shù)2]

這個方法是對行名進行索引。

data[0:2]
輸出:
    one two three   four
Ohio    0   1   2   3
Colorado    4   5   6   7

data[1:]
輸出:
    one two three   four
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15

3、[布爾表達式]

data[data['three']>5]
輸出:
    one two three   four
Colorado    4   5   6   7
Utah    8   9   10  11
New York    12  13  14  15

4、ix方法:DataFrame.ix['列名', ['索引名1',..., '索引名n']]

ix方法可以對index及columns都進行索引。

data.ix['Colorado', ['two', 'three']]
輸出:
two      5
three    6
Name: Colorado, dtype: int64

data.ix[['Colorado', 'Utah'], [1, 0, 3]]
輸出:
    two one four
Colorado    5   4   7
Utah    9   8   11

好了,Series和DataFrame的索引方法就總結(jié)到這里,自以為比書里的清晰一些吼吼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容