Pandas學習筆記(1)基本數據類型及屬性

Pandas介紹

Python Data Analysis Library即Pandas是基於NumPy 的一種Python數據分析工具包,包含豐富的數據類型和便捷的操作方式。

基本數據類型

Series

對應Python中的列表和NumPy的一維數組,Series可以指定索引內容,默認索引與Python相同從0開始的整形數

import pandas as pd

s = pd.Series([1,20,33,np.nan,5,66])
print(s)

output:
0     1.0
1    20.0
2    33.0
3     NaN
4     5.0
5    66.0
dtype: float64

可以使用自定義列表作爲索引參數,例如時間序列

dates = pd.date_range('20180205',periods=6)
s = pd.Series([1,3,6,np.nan,44,1],index=dates)
print(s)

output:
2018-02-05     1.0
2018-02-06    20.0
2018-02-07    33.0
2018-02-08     NaN
2018-02-09     5.0
2018-02-10    66.0
Freq: D, dtype: float64

之後可以通過索引訪問數據了

s['2018-2-07']

output:33.0

DataFrame

DataFrame提供表格類型的數據結構,相當於矩陣,NumPy裏的二維數組和Python的字典。和Series同樣的,DataFrame也有索引,包含行索引(index)和列索引(columns)。

DataFrame可以看做是由Series組成的大字典,二者關係類似於列向量和矩陣的關係。

默認索引與Series一致,均從0開始

df = pd.DataFrame(np.arange(12).reshape((3,4)))
print(df)

output:
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9   10  11

指定含參索引如下

df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])
print(df)

output:              
                 a         b         c         d
2018-02-05  0.350842  0.316069  0.283373 -1.171848
2018-02-06  0.557246 -2.338000  0.743795 -0.332596
2018-02-07 -0.056014  0.714417  2.609023  0.825786
2018-02-08 -0.638557  1.815248 -0.898888  1.120689
2018-02-09 -1.113309  1.315297 -1.694181  0.274465
2018-02-10 -0.640387 -0.098660 -2.717680 -0.017176

可調用屬性

  • dtype 查看每個列的數據類型

  • index 查看行索引及其數據類型

  • columns 查看列索引及其數據類型

  • values 以數組形式返回DataFrame的值(去索引)

  • describe 顯示數據的總結信息(均值,方差等)

  • transpose DataFrame的轉置

DataFrame類中定義了排序方法

df.sort_index(axis=0,ascending=False)

其中axis=0,代表按行排序,axis=1,代表按列排序
ascending=True代表正序,False代表逆序

還可以採用按值排序的方法

df.sort_values(by='E')

該方法按指定索引的值進行排序

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