pandas的series的增刪改查(5)

2021-09-29 15:59:58 字數 2998 閱讀 9905

curd的意思同資料庫中一樣,是建立、更新、讀取和刪除的意思。

標準的建立series的方式是用字串列表作為series物件的標識每個資料的方式,即label來標誌出每個資料。

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

print s

建立的series物件s為:

hello    10

the 11

cruel 12

world 13

dtype: int64

讀取series物件的label和value的方式有很多。

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

print s

print s["hello"]

s["hello"] = 100

s[1] = 110

print s

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

for x in s.iteritems():

print x

程式的執行結果如下:

('hello', 10)

('the', 11)

('cruel', 12)

('world', 13)

s["hello"] = 100

s[1] = 110

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

print s

s[0] = 100

s.loc["the"] = 101

s.at['cruel'] = 201

s.ix[3] = 300

print s

程式的執行結果如下:

hello    10

the 11

cruel 12

world 13

dtype: int64

hello 100

the 101

cruel 201

world 300

dtype: int64

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

print s, "<-org"

s.set_value("this", 8)

print s, "<-set_value"

程式執行結果:

hello    10

the 11

cruel 12

world 13

dtype: int64 <-org

hello 10

the 11

cruel 12

world 13

this 9

this 10

hello 10

the 11

cruel 12

world 13

this 8

this 8

dtype: int64 <-set_value

在series裡是允許label相同的。

刪除在series很少用。常用布林選擇或mask來選擇資料組成新的series。

import pandas as pd

idx = "hello the cruel world".split()

val = range(10, 14)

s = pd.series(val, index = idx)

print s, "<-org"

t = s[s > 11]

print t,"<- bool sel"

print s,"<- still"

執行結果:

hello    10

the 11

cruel 12

world 13

dtype: int64 <-org

cruel 12

world 13

dtype: int64 <- bool sel

hello 10

the 11

cruel 12

world 13

dtype: int64 <- still

新生成的t是通過t = s[s > 11]語句得到的(布林選擇),而s沒有變化。t為:

cruel    12

world 13

dtype: int64 <- bool sel

pandas中的Series物件

series和dataframe是pandas中最常用的兩個物件 1。可以用numpy的陣列處理函式直接對series物件進行處理 2。支援使用位置訪問元素,使用索引標籤作為下標訪問元素 每個series物件實際上都是由兩個陣列組成 1 index 從ndarray陣列繼承的index索引物件,儲存...

Pandas庫的使用 Series

一。概念 series相當於一維陣列。1.呼叫series的原生方法建立 import pandas as pd s1 pd.series data 1,2,4,6,7 index a b c d e index表示索引 print s1 a print s1 0 print s1 3 在serie...

pandas的資料結構 Series

要是用pandas,你首先得了解它的兩個主要資料結構 series和dataframe,這裡我將簡單介紹一下series series,python,pandas from pandas import series,dataframe import pandas as pd import numpy...