python基礎 - Pandas

Pandas 是基於 Numpy 創建的 Python 庫,爲 Python 提供了易於使用的數據結構和數據分析工具。

使用以下語句導入 Pandas 庫:

import pandas as pd

1、Pandas 數據結構

(1)Series - 序列

存儲任意類型數據的一維數組:

s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'])
index value
a 3
b -5
c 7
d 4

(2)DataFrame - 數據框

存儲不同類型數據的二維數組

data = {'Country': ['Belgium', 'India', 'Brazil'],
        'Capital': ['Brussels', 'New Delhi', 'Brasília'],
        'Population': [11190846, 1303171035, 207847528]}
df = pd.DataFrame(data, columns=['Country', 'Capital', 'Population'])
index Country Capital Population
0 Belgium Brussels 11190846
1 India New Delhi 1303171035
2 Brazil Brasília 207847528

2、輸入/輸出

詳細參考:https://blog.csdn.net/qq_19446965/article/details/106882889

(1)讀取/寫入CSV

pd.read_csv('test.csv', header=0, nrows=3)
df.to_csv('test.csv')

(2)讀取/寫入Excel

pd.read_excel('test.xlsx')
pd.to_excel('test.xlsx', sheet_name='Sheet1')
# 讀取內含多個表的Excel
xlsx = pd.ExcelFile('test.xls')
df = pd.read_excel(xlsx, 'Sheet1')

(3)讀取和寫入 SQL 查詢及數據庫表

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
pd.read_sql("SELECT * FROM my_table;", engine)
pd.read_sql_table('my_table', engine)
pd.read_sql_query("SELECT * FROM my_table;", engine)

read_sql()是 read_sql_table() 與 read_sql_query()的便捷打包器

pd.to_sql('myDf', engine)

3、選取、布爾索引及設置

s['b']  # 取序列的值 -5
df[1:]  # 取數據框的子集
#   Country    Capital  Population
# 1   India  New Delhi  1303171035
# 2  Brazil   Brasília   207847528

區域選取:

  區域選取可以從多個維度(行和列)對數據進行篩選,可以通過df.loc[],df.iloc[],df.ix[]三種方法實現。採用df.loc[],df.iloc[],df.ix[]這三種方法進行數據選取時,方括號內必須有兩個參數,第一個參數是對行的篩選條件,第二個參數是對列的篩選條件,兩個參數用逗號隔開。df.loc[],df.iloc[],df.ix[]的區別如下:

  • df.loc[]只能使用標籤索引,不能使用整數索引,通過便籤索引切邊進行篩選時,前閉後閉。
  • df.iloc[]只能使用整數索引,不能使用標籤索引,通過整數索引切邊進行篩選時,前閉後開。
  • df.ix[]既可以使用標籤索引,也可以使用整數索引。

單元格選取:

  單元格選取包括df.at[]和df.iat[]兩種方法。df.at[]和df.iat[]使用時必須輸入兩個參數,即行索引和列索引,其中df.at[]只能使用標籤索引,df.iat[]只能使用整數索引。df.at[]和df.iat[]選取的都是單個單元格(單行單列),所以返回值都爲基本數據類型

(1)按位置

df.iloc[[0], [0]]   # 按行與列的位置選擇某值:
#    Country
# 0  Belgium
df.iat[0, 0]    # 'Belgium'

(2)按標籤

df.loc[[0], ['Country']]
#    Country
# 0  Belgium
df.at[0, 'Country']         # 'Belgium'

(3)按標籤/位置

df.ix[2]
# Country Brazil
# Capital Brasília
# Population 207847528
df.ix[:, 'Capital']
# 0 Brussels
# 1 New Delhi
# 2 Brasília
df.ix[1, 'Capital']   # 'New Delhi'

(4)布爾索引

s[~(s > 1)]                         # 序列 S 中沒有大於1的值
# b   -5
s[(s < -1) | (s > 2)]               # 序列 S 中小於-1或大於2的值
# a    3
# b   -5
# c    7
# d    4
df[df['Population'] > 1200000000]   # 使用篩選器調整數據框
#   Country    Capital  Population
# 1   India  New Delhi  1303171035

4、刪除數據

s.drop(['a', 'c'])          # 按索引刪除序列的值 (axis=0)
df.drop('Country', axis=1)  # 按列名刪除數據框的列(axis=1)

5、排序和排名

df.sort_index()                 # 按索引排序
df.sort_values(by='Country')    # 按某列的值排序
df.rank()                       # 數據框排名
#    Country  Capital  Population
# 0      1.0      2.0         1.0
# 1      3.0      3.0         3.0
# 2      2.0      1.0         2.0

6、查詢序列與數據框的信息

(1)基本信息

df.shape        # (行,列))
# (3, 3)
df.index        # 獲取索引
# RangeIndex(start=0, stop=3, step=1)
df.columns      # 獲取列名
# Index(['Country', 'Capital', 'Population'], dtype='object')
df.info()       # 獲取數據框基本信息
# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 3 entries, 0 to 2
# Data columns (total 3 columns):
# Country       3 non-null object
# Capital       3 non-null object
# Population    3 non-null int64
df.count()      # 非Na值的數量
# Country       3
# Capital       3
# Population    3

(2)統計信息

df.sum()                  # 求和
df.cumsum()               # 累加
df.min()                  # 最小值
# Country        Belgium
# Capital       Brasília
# Population    11190846
df.max()                  # 最大值
# Country            India
# Capital        New Delhi
# Population    1303171035
df['Population'].idxmin() # 最小值索引: 0
df['Population'].idxmax() # 最大值索引: 1
df.mean()                 # 平均值
df.median()               # 中位數
df.describe()             # 基礎統計數據
#          Population
# count  3.000000e+00
# mean   5.074031e+08
# std    6.961346e+08
# min    1.119085e+07
# 25%    1.095192e+08
# 50%    2.078475e+08
# 75%    7.555093e+08
# max    1.303171e+09

7、應用函數 

df.apply(lambda x: x*2)       # 應用函數
df.applymap(lambda x: x*2)    # 對每個單元格應用函數
#           Country             Capital  Population
# 0  BelgiumBelgium    BrusselsBrussels    22381692
# 1      IndiaIndia  New DelhiNew Delhi  2606342070
# 2    BrazilBrazil    BrasíliaBrasília   415695056

8、數據對齊

如有不一致的索引,則使用NA值:

s3 = pd.Series([7, -2, 3], index=['a', 'c', 'd'])
s + s3
# a 10.0
# b NaN
# c 5.0
# d 7.0

 還可以使用 Fill 方法進行內部對齊運算:

s.add(s3, fill_value=0)
# a 10.0
# b -5.0
# c 5.0
# d 7.0
s.sub(s3, fill_value=2)
s.div(s3, fill_value=4)
s.mul(s3, fill_value=3)

摘自DataCamp
Learn Python for Data Science Interactively

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