Python數據分析實戰【第三章】2.2- Pandas數據結構Series:基本概念及創建【python】

【課程2.2】 Pandas數據結構Series:基本概念及創建

"一維數組"Serise

# Series 數據結構
# Series 是帶有標籤的一維數組,可以保存任何數據類型(整數,字符串,浮點數,Python對象等),軸標籤統稱爲索引

import numpy as np
import pandas as pd  
# 導入numpy、pandas模塊

s = pd.Series(np.random.rand(5))
print(s)
print(type(s))
# 查看數據、數據類型

print(s.index,type(s.index))
print(s.values,type(s.values))
# .index查看series索引,類型爲rangeindex
# .values查看series值,類型是ndarray

# 核心:series相比於ndarray,是一個自帶索引index的數組 → 一維數組 + 對應索引
# 所以當只看series的值的時候,就是一個ndarray
# series和ndarray較相似,索引切片功能差別不大
# series和dict相比,series更像一個有順序的字典(dict本身不存在順序),其索引原理與字典相似(一個用key,一個用index)
-----------------------------------------------------------------------
0    0.229773
1    0.357622
2    0.546116
3    0.734517
4    0.686645
dtype: float64
<class 'pandas.core.series.Series'>
RangeIndex(start=0, stop=5, step=1) <class 'pandas.indexes.range.RangeIndex'>
[ 0.22977307  0.35762236  0.54611623  0.73451707  0.68664496] <class 'numpy.ndarray'>

2.Series 創建方法一:由字典創建,字典的key就是index,values就是values

dic = {'a':1 ,'b':2 , 'c':3, '4':4, '5':5}
s = pd.Series(dic)
print(s)
# 注意:key肯定是字符串,假如values類型不止一個會怎麼樣? → dic = {'a':1 ,'b':'hello' , 'c':3, '4':4, '5':5}
-----------------------------------------------------------------------
4    4
5    5
a    1
b    2
c    3
dtype: int64

3.Series 創建方法二:由數組創建(一維數組)

arr = np.random.randn(5)
s = pd.Series(arr)
print(arr)
print(s)
# 默認index是從0開始,步長爲1的數字

s = pd.Series(arr, index = ['a','b','c','d','e'],dtype = np.object)
print(s)
# index參數:設置index,長度保持一致
# dtype參數:設置數值類型
-----------------------------------------------------------------------
[ 0.11206121  0.1324684   0.59930544  0.34707543 -0.15652941]
0    0.112061
1    0.132468
2    0.599305
3    0.347075
4   -0.156529
dtype: float64
a    0.112061
b    0.132468
c    0.599305
d    0.347075
e   -0.156529
dtype: object

4.Series 創建方法三:由標量創建

s = pd.Series(10, index = range(4))
print(s)
# 如果data是標量值,則必須提供索引。該值會重複,來匹配索引的長度
-----------------------------------------------------------------------
0    10
1    10
2    10
3    10
dtype: int64

5.Series 名稱屬性:name

s1 = pd.Series(np.random.randn(5))
print(s1)
print('-----')
s2 = pd.Series(np.random.randn(5),name = 'test')
print(s2)
print(s1.name, s2.name,type(s2.name))
# name爲Series的一個參數,創建一個數組的 名稱
# .name方法:輸出數組的名稱,輸出格式爲str,如果沒用定義輸出名稱,輸出爲None

s3 = s2.rename('hehehe')
print(s3)
print(s3.name, s2.name)
# .rename()重命名一個數組的名稱,並且新指向一個數組,原數組不變
-----------------------------------------------------------------------
0   -0.403084
1    1.369383
2    1.134319
3   -0.635050
4    1.680211
dtype: float64
-----
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: test, dtype: float64
None test <class 'str'>
0   -0.120014
1    1.967648
2    1.142626
3    0.234079
4    0.761357
Name: hehehe, dtype: float64
hehehe test
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章