3.1 Pandas 基本介紹

學(xué)習(xí)資料:

Numpy 和 Pandas 有什么不同

如果用 python 的列表和字典來作比較, 那么可以說 Numpy 是列表形式的,沒有數(shù)值標(biāo)簽,而 Pandas 就是字典形式。Pandas是基于Numpy構(gòu)建的,讓Numpy為中心的應(yīng)用變得更加簡單。

要使用pandas,首先需要了解他主要兩個(gè)數(shù)據(jù)結(jié)構(gòu):Series和DataFrame。

Series

import pandas as pd
import numpy as np
s = pd.Series([1,3,6,np.nan,44,1])

print(s)
"""
0     1.0
1     3.0
2     6.0
3     NaN
4    44.0
5     1.0
dtype: float64
"""


Series的字符串表現(xiàn)形式為:索引在左邊,值在右邊。由于我們沒有為數(shù)據(jù)指定索引。于是會(huì)自動(dòng)創(chuàng)建一個(gè)0到N-1(N為長度)的整數(shù)型索引。

DataFrame

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

print(df)
"""
                   a         b         c         d
2016-01-01 -0.253065 -2.071051 -0.640515  0.613663
2016-01-02 -1.147178  1.532470  0.989255 -0.499761
2016-01-03  1.221656 -2.390171  1.862914  0.778070
2016-01-04  1.473877 -0.046419  0.610046  0.204672
2016-01-05 -1.584752 -0.700592  1.487264 -1.778293
2016-01-06  0.633675 -1.414157 -0.277066 -0.442545
"""

DataFrame是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),它包含有一組有序的列,每列可以是不同的值類型(數(shù)值,字符串,布爾值等)。DataFrame既有行索引也有列索引, 它可以被看做由Series組成的大字典。

我們可以根據(jù)每一個(gè)不同的索引來挑選數(shù)據(jù), 比如挑選 b 的元素:

DataFrame 的一些簡單運(yùn)用

print(df['b'])

"""
2016-01-01   -2.071051
2016-01-02    1.532470
2016-01-03   -2.390171
2016-01-04   -0.046419
2016-01-05   -0.700592
2016-01-06   -1.414157
Freq: D, Name: b, dtype: float64
"""

我們在創(chuàng)建一組沒有給定行標(biāo)簽和列標(biāo)簽的數(shù)據(jù) df1:

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

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

這樣,他就會(huì)采取默認(rèn)的從0開始 index. 還有一種生成 df 的方法, 如下 df2:

df2 = pd.DataFrame({'A' : 1.,
                    'B' : pd.Timestamp('20130102'),
                    'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
                    'D' : np.array([3] * 4,dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train"]),
                    'F' : 'foo'})
                    
print(df2)

"""
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo
"""

這種方法能對每一列的數(shù)據(jù)進(jìn)行特殊對待. 如果想要查看數(shù)據(jù)中的類型, 我們可以用 dtype這個(gè)屬性:

print(df2.dtypes)

"""
df2.dtypes
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object
"""

如果想看對列的序號:

print(df2.index)

# Int64Index([0, 1, 2, 3], dtype='int64')

同樣, 每種數(shù)據(jù)的名稱也能看到:

print(df2.columns)

# Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')

如果只想看所有df2的值:

print(df2.values)

"""
array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)
"""

想知道數(shù)據(jù)的總結(jié), 可以用 describe():

df2.describe()

"""
         A    C    D
count  4.0  4.0  4.0
mean   1.0  1.0  3.0
std    0.0  0.0  0.0
min    1.0  1.0  3.0
25%    1.0  1.0  3.0
50%    1.0  1.0  3.0
75%    1.0  1.0  3.0
max    1.0  1.0  3.0
"""

如果想翻轉(zhuǎn)數(shù)據(jù), transpose:

print(df2.T)

"""                   
0                    1                    2  \
A                    1                    1                    1   
B  2013-01-02 00:00:00  2013-01-02 00:00:00  2013-01-02 00:00:00   
C                    1                    1                    1   
D                    3                    3                    3   
E                 test                train                 test   
F                  foo                  foo                  foo   

                     3  
A                    1  
B  2013-01-02 00:00:00  
C                    1  
D                    3  
E                train  
F                  foo  

"""

如果想對數(shù)據(jù)的 index 進(jìn)行排序并輸出:

print(df2.sort_index(axis=1, ascending=False))

"""
     F      E  D    C          B    A
0  foo   test  3  1.0 2013-01-02  1.0
1  foo  train  3  1.0 2013-01-02  1.0
2  foo   test  3  1.0 2013-01-02  1.0
3  foo  train  3  1.0 2013-01-02  1.0
"""

如果是對數(shù)據(jù) 值 排序輸出:

print(df2.sort_values(by='B'))

"""
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo
"""
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容