Pandas中的數據結構Series和DataFrame(數據酷客學習筆記)

創建Series對象

● 基本的方式爲:
pd.Series(data, index=index)
●data可以是很多類型:列表,ndarray,Python字典,標量值

從數組創建

import pandas as pd
a = pd.Series([150,62,31,20])
print(a)
print(a.values)
print(a.index)

0 150
1 62
2 31
3 20
dtype: int64
[150 62 31 20]
RangeIndex(start=0, stop=4, step=1)

從列表創建

import numpy as np
import pandas as pd
pd.Series(np.random.randn(4),index=['a','b','c','d']) # 指定的index必須與data長度相同,多出來的索引項用空值填充

a -0.333946
b 0.499868
c -0.356603
d -1.138034
dtype: float64

從字典創建

pd.Series({'a':1,'b':2,'c':3,'d':4})

a 1
b 2
c 3
d 4
dtype: int64

創建DataFrame對象

●基本的方式爲:
pd.DataFrame(data,index,columns)
●與Series不同, DataFrame包括索lindex和表頭columns
●data允許輸入以下一些格式:
》包含列表,字典或Series的字典
》二維數組
》一個Series對象
》另一個DataFrame對象

pd.Series(2,index=['a','b','c'])

a    2
b    2
c    2
dtype: int64

# Series在算術運算中會自動對齊不同索引的數據。

a1 = pd.Series([1,2,3,4],index=['a','b','c','d'])

a2 = pd.Series([4,3,2,1],index=['d','c','b','a'])

print(a1+a2)

a    2
b    4
c    6
d    8
dtype: int64

# 可以使用unique()去重 用values_counts()統計每個數據頻數 用astype()轉換類型 

b = {'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,4],index=['a','b','d'])}

m = pd.DataFrame(b)

print(m)

print(m.index)

print(m.columns)

   one  two
a  1.0  1.0
b  2.0  2.0
c  3.0  NaN
d  NaN  4.0
Index(['a', 'b', 'c', 'd'], dtype='object')
Index(['one', 'two'], dtype='object')

m['three']=m['one']+m['two']

m['f'] = m['one']>1

print(m)

   one  two  three      f
a  1.0  1.0    2.0  False
b  2.0  2.0    4.0   True
c  3.0  NaN    NaN   True
d  NaN  4.0    NaN  False

m.insert(1,'bar',m['one'])

m

	one 	bar 	two 	three 	f
a 	1.0 	1.0 	1.0 	2.0 	False
b 	2.0 	2.0 	2.0 	4.0 	True
c 	3.0 	3.0 	NaN 	NaN 	True
d 	NaN 	NaN 	4.0 	NaN 	False

del m['f']

m

	one 	bar 	two 	three
a 	1.0 	1.0 	1.0 	2.0
b 	2.0 	2.0 	2.0 	4.0
c 	3.0 	3.0 	NaN 	NaN
d 	NaN 	NaN 	4.0 	NaN

bar = m.pop('bar')

bar

a    1.0
b    2.0
c    3.0
d    NaN
Name: bar, dtype: float64

索引

# 通過標籤選取某一行/列

b = {'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,4],index=['a','b','d'])}

m = pd.DataFrame(b)

m

	one 	two
a 	1.0 	1.0
b 	2.0 	2.0
c 	3.0 	NaN
d 	NaN 	4.0

m.loc['a']

one    1.0
two    1.0
Name: a, dtype: float64

m.loc['a','one']

1.0
# df,iloc[loc] :通過位置(整數表示)獲取某-/,其中字母”"表示"index"。記住在這種方式下,一定要用整數或者整數列表進行索引。

Panel

●Panel(面板) 是一 種三維數據容器。
●Panel 數據結構借鑑了經濟計量學中的面板數據結構。- -個Panel對象主要由
三個軸構成:
●items- axis0 ,每個項目對應於內部包含的DataFrame。
●major_axis - axis1,它是每個DataFrame的索引(行)。
●minor_axis - axis2 ,它是每個DataFrame的列。

創建:np.panel()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章