pandas資料結構之Series

2021-08-13 02:05:45 字數 2983 閱讀 8598

series 是一種類似於一維陣列的物件,它由一組資料和一組與之相關的資料標籤(lable)或者說索引(index)組成。

現在我們使用series生成乙個最簡單的series物件,因為沒有給series指定索引,所以此時會使用預設索引(從0到n-1)。

>>> 

from pandas import series,dataframe

>>>

import pandas as pd

>>> obj = series([3, 0, 5, 8])

>>> obj03

1025

38dtype: int64

我們還可以生成乙個指定索引(index)的series:

>>> 

from pandas import series,dataframe

>>>

import pandas as pd

>>> obj = series(range(4), index=['a','b','c','d'])

>>> obj

a 0

b 1

c 2

d 3

dtype: int64

我們也可以通過字典來建立series物件,可以發現,用字典建立的series是按index有序的:

>>> 

from pandas import series,dataframe

>>>

import pandas as pd

>>> dic =

>>> obj = series(dic)

>>> obj

a 1

b 2

c 3

d 4

dtype: int64

在用字典生成series的時候,也可以指定索引,當索引中值對應的字典中的值不存在的時候,則此索引的值標記為nan,並且可以通過函式(pandas.isnull,pandas.notnull)來確定哪些索引對應的值是不存在的。

>>> 

from pandas import series,dataframe

>>>

import pandas as pd

>>> index_1 = ['a','b','c','what','d']

>>> obj = series(dic,index=index_1)

>>> obj

a 1.0

b 2.0

c 3.0

what nan

d 4.0

dtype: float64

# 使用pandas下的isnull()函式判斷哪個值為空

>>> pd.isnull(obj)

a false

b false

c false

what true

d false

dtype: bool

# 使用pandas下的notnull()函式判斷哪個值不為空

>>> pd.notnull(obj)

a true

b true

c true

what false

d true

dtype: bool

我們還可以訪問series中的元素和索引:

# 訪問obj中索引為a的值

>>> obj['a']

1.0# 訪問obj中索引為a和索引為d的值

>>> obj[['a','d']]

a 1.0

d 4.0

dtype: float64

# 獲取所有的值

>>> obj.values

array([ 1., 2., 3., nan, 4.])

# 獲取所有的索引

>>> obj.index

index([u'a', u'b', u'c', u'what', u'd'], dtype='object')

對於許多應用而言,series的乙個重要功能就是自動對齊,看看下面的例子就明白了。 不同series物件運算的時候根據其索引進行匹配計算。

>>> obj

a 1.0

b 2.0

c 3.0

what nan

d 4.0

dtype: float64

>>> obj1

d 0

b 1

what 2

c 3

a 4

dtype: int64

# 將obj和obj1相加,發現,series在算數運算中會自動對齊不同索引的資料

>>> obj+obj1

a 5.0

b 3.0

c 6.0

d 4.0

what nan

dtype: float64

series物件本身,以及索引都有乙個 name 屬性

>>> obj.index.name='name'

>>> obj.name='test'

>>> obj

name

a 1.0

b 2.0

c 3.0

what nan

d 4.0

name: test, dtype: float64

Pandas資料結構之Series

import pandas as pd series類 生成series類的方法 1.obj pd.series 4,7,5,3 obj2 pd.series 4,7,5,3 index a b c d print obj2.values,obj2.index print obj2 a print ...

pandas資料結構之Dataframe

綜述 numpy主要用於進行運算 dataframe更切合於業務邏輯 dataframe的常用的屬性 屬性 說明 shape dataframe的形狀 values dataframe的值,numpy.ndarray index 行索引 index.name 行索引的名字 columns 列索引 c...

pandas資料結構之DataFrame筆記

dataframe輸出的為表的形式,由於要把輸出的 貼上來比較麻煩,在此就不在貼出相關輸出結果,在jupyter notebook可以順利執行 中有相關解釋用來加深理解方便記憶1 import numpy as np 2import pandas as pd 34 d 67 df pd.datafr...