pandas庫
pandas是python第三方庫,提供高性能易用數(shù)據(jù)類型和分析工具。
pandas基于numpy實(shí)現(xiàn),常與numpy和matplotlib一同使用
更多學(xué)習(xí),請參考pandas中文網(wǎng):https://www.pypandas.cn/
Pandas核心數(shù)據(jù)結(jié)構(gòu)
1. Series
Series是一種類似于一維數(shù)組的對象,它由一維數(shù)組(各種numpy數(shù)據(jù)類型)以及一組與之相關(guān)的數(shù)據(jù)標(biāo)簽(即索引)組成.
可理解為帶標(biāo)簽的一維數(shù)組,可存儲整數(shù)、浮點(diǎn)數(shù)、字符串、Python 對象等類型的數(shù)據(jù)。
import pandas as pd
import numpy as np
s = pd.Series(['a','b','c','d','e'])
print(s)
0 a
1 b
2 c
3 d
4 e
dtype: object
Seris中可以使用index設(shè)置索引列表。
#與字典不同的是:Series允許索引重復(fù)
s = pd.Series(['a','b','c','d','e'],index=[100,200,100,400,500])
print(s)
100 a
200 b
100 c
400 d
500 e
dtype: object
Series 可以用字典實(shí)例化
d = {'b': 1, 'a': 0, 'c': 2}
pd.Series(d)
b 1
a 0
c 2
dtype: int64
可以通過Series的values和index屬性獲取其數(shù)組表示形式和索引對象
print(s)
print(s.values)
print(s.index)
100 a
200 b
100 c
400 d
500 e
dtype: object
['a' 'b' 'c' 'd' 'e']
Int64Index([100, 200, 100, 400, 500], dtype='int64')
Series中最重要的一個(gè)功能是:它會在算術(shù)運(yùn)算中自動對齊不同索引的數(shù)據(jù)
Series 和多維數(shù)組的主要區(qū)別在于, Series 之間的操作會自動基于標(biāo)簽對齊數(shù)據(jù)。因此,不用顧及執(zhí)行計(jì)算操作的 Series 是否有相同的標(biāo)簽。
obj1 = pd.Series({"Ohio": 35000, "Oregon": 16000, "Texas": 71000, "Utah": 5000})
print(obj1)
obj2 = pd.Series({"California": np.nan, "Ohio": 35000, "Oregon": 16000, "Texas": 71000})
print(obj2)
print(obj1 + obj2)
2.DataFrame
DataFrame
DataFrame是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),類似于Excel或sql表
它含有一組有序的列,每列可以是不同的值類型(數(shù)值、字符串、布爾值等)
DataFrame既有行索引也有列索引,它可以被看做由Series組成的字典(共用同一個(gè)索引)
用多維數(shù)組字典、列表字典生成
pd.DataFrame()
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = pd.DataFrame(data)
print(frame)
#如果指定了列順序,則DataFrame的列就會按照指定順序進(jìn)行排列
frame1 = pd.DataFrame(data, columns=['year', 'state', 'pop'])
print(frame1)
跟原Series一樣,如果傳入的列在數(shù)據(jù)中找不到,就會產(chǎn)生NAN(Not of Number)值
frame2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five'])
print(frame2)
用 Series 字典或字典生成 DataFrame
d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
print(pd.DataFrame(d))
#通過類似字典標(biāo)記的方式或?qū)傩缘姆绞剑梢詫ataFrame的列獲取為一個(gè)Series,返回的Series擁有原DataFrame相同的索引
print(frame2['state'])
列可以通過賦值的方式進(jìn)行修改,例如,給那個(gè)空的“delt”列賦上一個(gè)標(biāo)量值或一組值
frame2['debt'] = 16.5
print(frame2)
print(frame2)
frame2['new'] = frame2['debt' ]* frame2['pop']
print(frame2)
frame2['debt'] = np.arange(5.)
print(frame2)