初探pandas 安裝和了解pandas資料結構

2022-07-26 02:18:11 字數 3331 閱讀 4269

通過python pip安裝pandas

pip install pandas
pandas常用資料結構包括:series和dataframe

series是一種一維的陣列型物件,包含乙個值序列(與numpy中的資料型別相似),資料標籤(稱為索引(index))。

import pandas as pd

# 建立series物件

obj=pd.series([4,5,6,7])

print(obj)

0    4

1 5

2 6

3 7

dtype: int64

左邊為索引,右邊為值,預設索引從0到n-1(n為資料長度),可以通過values屬性和index屬性分別獲得series物件的值和索引

print(obj.values)
array([4, 5, 6, 7], dtype=int64)
print(obj.index)
rangeindex(start=0, stop=4, step=1)
# 自定義索引序列

obj2=pd.series([4,5,6,7],index=['a','b','d','e'])

print(obj2,'\n')

# 輸出索引

print(obj2.index)

a    4

b 5

d 6

e 7

dtype: int64

index(['a', 'b', 'd', 'e'], dtype='object')

series物件可以使用標籤來進行索引

# 輸出索引為b的元素

print(obj2['b'])

# 輸出索引為a,d,e的元素

print('* '*10)

print(obj2[['a','d','e']])

5

* * * * * * * * * *

a 4

d 6

e 7

dtype: int64

series物件也能使用布林值進行過濾

# 輸出值大於5的元素

print(obj2[obj2>5])

d    6

e 7

dtype: int64

dataframe表示矩陣的資料表,包含已排序的列集合,每一列可以是不同的的值型別(數值、字串、布林值等)

dataframe既有行索引,也有列索引,可以被視為乙個共享相同索引的series的字典

# 建立dataframe物件

data=

frame=pd.dataframe(data)

print(frame)

age name  height

0 18 a 180

1 18 b 180

2 18 c 180

3 20 aa 182

4 20 bb 182

5 20 cc 182

dataframe也可以用columns引數指定列索引順序排列

frame=pd.dataframe(data,columns=['name','age','height'])

print(frame)

name  age  height

0 a 18 180

1 b 18 180

2 c 18 180

3 aa 20 182

4 bb 20 182

5 cc 20 182

如果傳的列引數不在字典中,將會出現缺失值

frame=pd.dataframe(data,columns=['name','age','height','addition'])

print(frame)

print(frame.columns)

name  age  height addition

0 a 18 180 nan

1 b 18 180 nan

2 c 18 180 nan

3 aa 20 182 nan

4 bb 20 182 nan

5 cc 20 182 nan

index(['name', 'age', 'height', 'addition'], dtype='object')

dataframe的一列可以按字典型標記或屬性那樣索引為series

frame=pd.dataframe(data,columns=['name','age','height'])

print(frame['name'])

print(frame.age)

0     a

1 b

2 c

3 aa

4 bb

5 cc

name: name, dtype: object

0 18

1 18

2 18

3 20

4 20

5 20

name: age, dtype: int64

行也可以通過位置或特殊屬性loc進行索引

frame=pd.dataframe(data,columns=['name','age','height'])

print(frame.loc[2])

name        c

age 18

height 180

name: 2, dtype: object

初探pandas 安裝和了解pandas資料結構

通過python pip安裝pandas pip install pandaspandas常用資料結構包括 series和dataframe series是一種一維的陣列型物件,包含乙個值序列 與numpy中的資料型別相似 資料標籤 稱為索引 index import pandas as pd 建立...

初探pandas 索引和查詢資料

利用pandas查詢資料 import pandas as pd ser pd.series range 0 10,2 print ser 0 0 1 2 2 4 3 6 4 8 dtype int64通過index檢視索引值 print ser.index rangeindex start 0,s...

Python資料分析Pandas庫資料結構 一

import pandas as pd import numpy as np s pd.series 1,2,3,4,np.nan,9,9 s2 pd.date range 20181201 periods 6 periods週期 import pandas as pd import numpy a...