1. 程式人生 > 實用技巧 >Pandas系列教程(3)Pandas資料查詢

Pandas系列教程(3)Pandas資料查詢

Pandas資料查詢

pandas 查詢資料的幾種方法

  1. df.loc方法,根據行,列的標籤值查詢

  2. df.iloc方法,根據行,列的數字位置查詢

  3. df.where方法

  4. df.query方法

.loc即可以查詢,又能覆蓋雪茹,強烈推薦

pandas 使用df.loc查詢資料的方法

  1. 使用單個label值查詢資料

  2. 使用值列表批量查詢

  3. 使用數值區間進行範圍查詢

  4. 使用條件表示式查詢

  5. 呼叫函式查詢

注意:

  • 以上查詢方法,即適用於行,也適用於列

  • 注意觀察降維DataFrame>Series>值

1、讀取資料

import pandas as pd

file_path 
= "../files/beijing_tianqi_2018.csv" df = pd.read_csv(file_path) print("列印前幾行的資料:\n ", df.head()) # 設定索引為日期,方便按日期篩選 df.set_index('ymd', inplace=True) # 時間序列見後續課程,本次按字串處理 print("列印索引:\n ", df.index) print("列印前幾行的資料:\n ", df.head()) # 替換溫度的字尾℃ df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('
', '').astype('int32') df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32') print("列印每列的資料型別:\n ", df.dtypes) print("列印前幾行的資料:\n ", df.head())

2、使用單個label值查詢資料

行或者列,都可以只傳單個值,實現精確匹配

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理 # 設定索引為日期,方便按日期篩選 df.set_index('ymd', inplace=True) # 替換溫度的字尾℃ df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32') df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32') # 列印前幾行資料 print(df.head()) # 得到單個值(獲取2018-01-03的最高溫度) print(df.loc['2018-01-03', 'bWendu']) # 得到一個Series(獲取2018-01-03的最高溫度和最低溫度) print(df.loc['2018-01-03', ['bWendu', 'yWendu']])

3、使用值列表批量查詢

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理
# 設定索引為日期,方便按日期篩選
df.set_index('ymd', inplace=True)
# 替換溫度的字尾℃
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 列印前幾行資料
print(df.head())

# 得到Series(獲取['2018-01-03', '2018-01-04', '2018-01-05']的最高溫度)
print(df.loc[['2018-01-03', '2018-01-04', '2018-01-05'], 'bWendu'])

# 得到DataFrame(獲取['2018-01-03', '2018-01-04', '2018-01-05']的最高溫度和最低溫度)
print(df.loc[['2018-01-03', '2018-01-04', '2018-01-05'], ['bWendu', 'yWendu']])

4、使用數值區間進行範圍查詢

注意:區間即包含開始,也包含結束

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理
# 設定索引為日期,方便按日期篩選
df.set_index('ymd', inplace=True)
# 替換溫度的字尾℃
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 列印前幾行資料
print(df.head(), '\n', '*' * 50)

# 行index按區間
print(df.loc['2018-01-03':'2018-01-05', 'bWendu'], '\n', '*' * 50)

# 列index按區間
print(df.loc['2018-01-03', 'bWendu':'fengxiang'], '\n', '*' * 50)

# 行列都按區間查詢
print(df.loc['2018-01-03':'2018-01-05', 'bWendu':'fengxiang'])

5、使用條件表示式查詢

bool列表的長度等於行數或者列數

簡單條件查詢

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理
# 設定索引為日期,方便按日期篩選
df.set_index('ymd', inplace=True)
# 替換溫度的字尾℃
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 簡單查詢, 最低溫度低於-10度的列表
print(df.loc[df['yWendu'] < -10, :], '\n', '*' * 50)

# 觀察一下這裡的boolean條件
print(df['yWendu'] < -10, '\n', '*' * 50)

複雜條件查詢

注意:組合條件用&符號合併,每個條件判斷都得帶括號

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理
# 設定索引為日期,方便按日期篩選
df.set_index('ymd', inplace=True)
# 替換溫度的字尾℃
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 查詢最高溫度小於30度,並且最低溫度大於十五度,並且是晴天,並且天氣為優的資料
print(df.loc[(df['bWendu'] <= 30) & (df['yWendu'] >= 15) & (df['tianqi'] == '') & (df['aqiLevel'] == 1), :])
print('*' * 50)

# 觀察一下這裡的boolean條件
print((df['bWendu'] <= 30) & (df['yWendu'] >= 15) & (df['tianqi'] == '') & (df['aqiLevel'] == 1))

6、呼叫函式查詢

import pandas as pd

file_path = "../files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)
# 資料的預處理
# 設定索引為日期,方便按日期篩選
df.set_index('ymd', inplace=True)
# 替換溫度的字尾℃
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 直接寫lambda表示式
print(df.loc[lambda df: (df['bWendu'] <= 30) & (df['yWendu'] >= 15), :])
print('*' * 50)

# 編寫自己的函式,查詢9月份,空氣質量好的資料
def query_my_data(df):
    return df.index.str.startswith('2018-09') & df['aqiLevel'] == 1
print(df.loc[query_my_data, :])