關(guān)于Pandas版本: 本文基于 pandas2.2.0 編寫。
關(guān)于本文內(nèi)容更新: 隨著pandas的stable版本更迭,本文持續(xù)更新,不斷完善補(bǔ)充。
傳送門: Pandas API參考目錄
傳送門: Pandas 版本更新及新特性
傳送門: Pandas 由淺入深系列教程
Pandas.DataFrame.loc[]
Pandas.DataFrame.loc[]
方法用于通過索引、列名 篩選 DataFrame
數(shù)據(jù)。
- 注意!在此方法中,你傳遞的數(shù)字,不會(huì)被理解為
自然索引
,只作為字符串傳遞給DataFrame.loc
視為行索引的值,或列名的值。 -
?? 注意 :
- 在此方法中,你傳遞的數(shù)字,不會(huì)被理解為
自然索引
,只作為字符串傳遞給DataFrame.loc
視為行索引的值,或列名的值。 - 如果對(duì)具有
多層索引
的DataFrame
進(jìn)行范圍篩選,必須先對(duì)其進(jìn)行排序 推薦使用df.sort_index(inplace=True)
排序后再進(jìn)行范圍篩選。 - 支持篩選后對(duì)原數(shù)據(jù)進(jìn)行賦值 例10
- 在此方法中,你傳遞的數(shù)字,不會(huì)被理解為
語法:
DataFrame.loc [‘行索引’,‘列名’]
返回值:
-
Series or DataFrame or Scalar
- 篩選范圍、
DataFrame
是否具有多層索引等都會(huì)影響具體的返回形式。 - 如果篩選結(jié)果是
Series
或Scalar
時(shí),篩選條件套上 [ ] 方括號(hào),可以強(qiáng)制以DataFrame
樣式返回。例1
- 篩選范圍、
語法說明:
1、篩選1行,篩選1列,篩選單元格
-
DataFrame.loc[索引,列名] 例1
索引篩選條件、列名篩選條件,用英文逗號(hào)分隔。
-
篩選1行: DataFrame.loc[‘索引’,: ] 只傳遞索引條件時(shí),紅色逗號(hào)、冒號(hào)可以省略。紅色的冒號(hào)表示所有列。
-
篩選1列: DataFrame.loc[:, ‘列名’] 紅色冒號(hào)必須有,表示所有行。
-
篩選單元格: DataFrame.loc[‘索引’, ‘列名’]
如果
DataFrame
有多層索引、列名,當(dāng)你想篩選非頂層數(shù)據(jù)時(shí),需要用元組
傳遞索引、列名的層級(jí)。例2
-
2、篩選多行,篩選多列
-
DataFrame.loc[[‘索引1’,‘索引2’, …],[‘列名1’,‘列名2’, …]]例3
多個(gè)索引篩選條件用方括號(hào)包裹、多個(gè)列名篩選條件用方括號(hào)包裹。兩種條件用英文逗號(hào)分隔。
- 篩選多行: DataFrame.loc[[‘索引1’,‘索引2’, …], ] 只傳遞索引條件時(shí),紅色逗號(hào)可以省略。
- 篩選多列: DataFrame.loc[, [‘列名1’,‘列名2’, …]]
- 同時(shí)篩選多行多列: DataFrame.loc[[‘索引1’,‘索引2’, …], [‘列名1’,‘列名2’, …]]
-
?? 注意 :
-
多個(gè)條件,必須用 [ ] 方括號(hào)包裹!
-
與
Python切片
不同,被 [ ] 包裹的開始和結(jié)束位置的元素,都會(huì)包含在篩選條件內(nèi)。 -
如果
DataFrame
有多層索引、列名,當(dāng)你想篩選非頂層數(shù)據(jù)時(shí),需要用元組
傳遞索引、列名的層級(jí)。例4
-
3、范圍篩選
-
DataFrame.loc[[‘索引1’:‘索引2’] 例5
支持行的范圍篩選,開始和結(jié)束的范圍用英文冒號(hào)分隔。不支持列的范圍篩選。
-
只篩選行范圍: DataFrame.loc[[‘索引1’:‘索引2’], ] 只傳遞索引條件時(shí),紅色逗號(hào)可以省略。
-
篩選行范圍 + 篩選1列: DataFrame.loc[[‘索引1’:‘索引2’], ‘列名1’]
-
篩選行范圍 + 篩選多列: DataFrame.loc[[‘索引1’:‘索引2’], [‘列名1’,‘列名2’, …]]
-
?? 注意 :
-
開始和結(jié)束的范圍,必須用 : 英文冒號(hào)分隔!
-
范圍,必須用 [ ] 方括號(hào)包裹!
-
與
Python切片
不同,被 [ ] 包裹的范圍,開始和結(jié)束位置,都會(huì)包含在篩選條件內(nèi)。
-
如果
DataFrame
有多層索引、列名,起始范圍,必須精確到最底層的索引或列名。因?yàn)轫攲铀饕?、列名,可能代表著多行或多列,這是不能作為開始條件使用的。例6如果對(duì)具有
多層索引
的DataFrame
進(jìn)行范圍篩選,必須先對(duì)其進(jìn)行排序 推薦使用df.sort_index(inplace=True)
排序后再進(jìn)行范圍篩選。 -
4、布爾篩選
-
DataFrame.loc[行條件,列條件]
-
行篩選: 可以傳遞一個(gè)與行索引長(zhǎng)度相同的
布爾列表
表示那些行留下,哪些行舍棄。例7 - 行篩選: 可以使用布爾運(yùn)算對(duì)行進(jìn)行篩選。如果布爾運(yùn)算的數(shù)量超過3個(gè),建議使用 advanced indexing
-
?? 注意 :
行的布爾運(yùn)算,是通過列名完成的。以
df[列名]
的方式表達(dá)。 例8多個(gè)條件,可以用
&
,|
表示并或,不能使用and
,or
。例8
- 列篩選: 不支持布爾運(yùn)算。
-
行篩選: 可以傳遞一個(gè)與行索引長(zhǎng)度相同的
5、Callable 篩選
-
DataFrame.loc[Callable]
可以使用
Callable
進(jìn)行篩選,原理上這也是一種布爾篩選。 例9
相關(guān)方法:
?? 相關(guān)方法
DataFrame.at
Access a single value for a row/column label pair.
DataFrame.iloc
篩選數(shù)據(jù)-自然索引法
DataFrame.xs
Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.
Series.loc
Access group of values using labels.
示例:
測(cè)試文件下載:
本文所涉及的測(cè)試文件,如有需要,可在文章頂部的綁定資源處下載。
若發(fā)現(xiàn)文件無法下載,應(yīng)該是資源包有內(nèi)容更新,正在審核,請(qǐng)稍后再試。或站內(nèi)私信作者索要。
read_excel_na_values
例1:只有單層索引的DataFrame,篩選單條數(shù)據(jù)
- 1、篩選1行,默認(rèn)返回
Series
,把篩選條件套上 [ ],可以強(qiáng)制返回DataFrame
。
import pandas as pd
# 構(gòu)建DF
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
# 常規(guī)單行篩選,返回Series
df.loc['cobra']
# ... max_speed 1
# ... shield 2
# ... Name: cobra, dtype: int64
# 單行篩選,條件套上[ ],強(qiáng)制返回 DataFrame
df.loc[['cobra']]
# ... max_speed shield
# ... cobra 1 2
- 2、篩選1列,默認(rèn)返回
Series
,把篩選條件套上 [ ],可以強(qiáng)制返回DataFrame
。
# 常規(guī)單列篩選'max_speed',返回Series
df.loc[:,'max_speed']
# ... cobra 1
# ... viper 4
# ... sidewinder 7
# ... Name: max_speed, dtype: int64
# 單列篩選,條件套上[ ],強(qiáng)制返回 DataFrame
df.loc[:,['max_speed']]
# ... max_speed
# ... cobra 1
# ... viper 4
# ... sidewinder 7
- 3、篩選單元格,默認(rèn)返回標(biāo)量值
Scalar
,把篩選條件套上 [ ],可以強(qiáng)制返回DataFrame
。
# 常規(guī)單元格篩選,返回標(biāo)量值
df.loc['cobra', 'max_speed']
# ... 1
# 把篩選條件套上 [ ],可以強(qiáng)制返回 DataFrame
df.loc[['cobra'], ['max_speed']]
# ... max_speed
# ... cobra 1
例2:多層索引的DataFrame,篩選數(shù)據(jù)
- 1、構(gòu)建演示數(shù)據(jù)并觀察數(shù)據(jù)內(nèi)容
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
tuples = [
('射手', '巨魔族'), ('射手', '死靈族'),
('法師', '巨魔族'), ('法師', '死靈族'),
('戰(zhàn)士', '巨魔族'), ('戰(zhàn)士', '死靈族')
]
index = pd.MultiIndex.from_tuples(tuples)
values = [[9, 20], [10, 18], [7, 23],
[6, 25], [4, 30], [3, 35]]
df = pd.DataFrame(values, columns=[['屬性1','屬性2'], ['攻速','攻擊力']], index=index)
# 觀察數(shù)據(jù)內(nèi)容
df
- 2、篩選1行或1列頂層索引,正常傳遞條件即可
# 篩選頂層行索引
df.loc['射手']
# ... 屬性1 屬性2
# ... 攻速 攻擊力
# ... 巨魔族 9 20
# ... 死靈族 10 18
# 篩選頂層列索引
df.loc[:,'屬性1']
# ... 攻速
# ... 射手 巨魔族 9
# ... 死靈族 10
# ... 法師 巨魔族 7
# ... 死靈族 6
# ... 戰(zhàn)士 巨魔族 4
# ... 死靈族 3
- 2、篩選非頂層索引、列名,需要用元組把條件套起來
# 篩選最底層的某行
df.loc[('射手','巨魔族')]
# ... 屬性1 攻速 9
# ... 屬性2 攻擊力 20
# ... Name: (射手, 巨魔族), dtype: int64
# 篩選底層索引,頂層列名
df.loc[('射手','巨魔族'),'屬性1']
# ... 攻速 9
# ... Name: (射手, 巨魔族), dtype: int64
# 篩選底層索引,底層列名
df.loc[('射手','巨魔族'),('屬性1','攻速')]
# ... 9
9
- 3、多層索引篩選,條件用 [] 套起來,也可以強(qiáng)制返回
DataFrame
df.loc[[('射手','巨魔族')],['屬性1']]
# ... 屬性1
# ... 攻速
# ... 射手 巨魔族 9
例3:?jiǎn)螌铀饕腄ataFrame,篩選多條數(shù)據(jù)
import pandas as pd
# 構(gòu)建DF
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
# 篩選多行
df.loc[['cobra', 'viper']]
# ... max_speed shield
# ... cobra 1 2
# ... viper 4 5
# 篩選多行、單列
df.loc[['cobra', 'viper'],'max_speed']
# ... cobra 1
# ... viper 4
# ... Name: max_speed, dtype: int64
# 篩選多行、多列
df.loc[['cobra', 'viper'],['max_speed', 'shield']]
# ... max_speed shield
# ... cobra 1 2
# ... viper 4 5
例4:多層索引的DataFrame,篩選多條數(shù)據(jù)
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
tuples = [
('射手', '巨魔族'), ('射手', '死靈族'),
('法師', '巨魔族'), ('法師', '死靈族'),
('戰(zhàn)士', '巨魔族'), ('戰(zhàn)士', '死靈族')
]
index = pd.MultiIndex.from_tuples(tuples)
values = [[9, 20], [10, 18], [7, 23],
[6, 25], [4, 30], [3, 35]]
df = pd.DataFrame(values, columns=[['屬性1','屬性2'], ['攻速','攻擊力']], index=index)
# 篩選多個(gè)頂層行索引
df.loc[['射手','法師']]
# ... 屬性1 屬性2
# ... 攻速 攻擊力
# ... 射手 巨魔族 9 20
# ... 死靈族 10 18
# ... 法師 巨魔族 7 23
# ... 死靈族 6 25
# 篩選多個(gè)底層航索引
df.loc[[('射手','巨魔族'),('法師','死靈族')]]
# ... 屬性1 屬性2
# ... 攻速 攻擊力
# ... 射手 巨魔族 9 20
# ... 法師 死靈族 6 25
# 行、列組合條件
df.loc[('射手','巨魔族'),('屬性2','攻擊力')]
# ... 20
# 同時(shí)篩選多行、多列
df.loc[[('射手','巨魔族'),('法師','死靈族')],[('屬性1','攻速'),('屬性2','攻擊力')]]
# ... 屬性1 屬性2
# ... 攻速 攻擊力
# ... 射手 巨魔族 9 20
# ... 法師 死靈族 6 25
例5:?jiǎn)螌铀饕腄ataFrame,篩選行范圍
import pandas as pd
# 構(gòu)建DF
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
# 只篩選行的范圍
df.loc['viper':'sidewinder']
# ... max_speed shield
# ... viper 4 5
# ... sidewinder 7 8
# 行范圍 + 1列
df.loc['viper':'sidewinder','shield']
# ... viper 5
# ... sidewinder 8
# ... Name: shield, dtype: int64
# 行范圍 + 多列
df.loc['viper':'sidewinder',['max_speed','shield']]
# ... max_speed shield
# ... viper 4 5
# ... sidewinder 7 8
例6:多層索引的DataFrame,篩選行范圍 起始范圍,必須精確到最底層的索引或列名。
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
tuples = [
('射手', '巨魔族'), ('射手', '死靈族'),
('戰(zhàn)士', '巨魔族'), ('戰(zhàn)士', '死靈族'),
('法師', '巨魔族'), ('法師', '死靈族')
]
index = pd.MultiIndex.from_tuples(tuples)
values = [[9, 20], [10, 18], [7, 23],
[6, 25], [4, 30], [3, 35]]
df = pd.DataFrame(values, columns=[['屬性1','屬性2'], ['攻速','攻擊力']], index=index)
# 觀察數(shù)據(jù)
# df
# 屬性1 屬性2
# 攻速 攻擊力
# 射手 巨魔族 9 20
# 死靈族 10 18
# 戰(zhàn)士 巨魔族 4 30
# 死靈族 3 35
# 法師 巨魔族 7 23
# 死靈族 6 25
# 篩選從射手到法師,即使都是頂層索引,范圍條件的開始位置,也必須精確到巨魔族,意為指定這一行。因?yàn)轫攲铀饕⒘忻?,可能代表著多行或多列,這是不能作為開始條件使用的。
df.loc[('射手','巨魔族'):'戰(zhàn)士']
# 屬性1 屬性2
# 攻速 攻擊力
# 射手 巨魔族 9 20
# 死靈族 10 18
# 戰(zhàn)士 巨魔族 4 30
# 死靈族 3 35
# 篩選行范圍 + 列范圍
df.loc[('射手','巨魔族'):('戰(zhàn)士', '巨魔族'),('屬性1','攻速'):('屬性2', '攻擊力')]
# 屬性1 屬性2
# 攻速 攻擊力
# 射手 巨魔族 9 20
# 死靈族 10 18
# 戰(zhàn)士 巨魔族 4 30
示例7:傳遞布爾列表,表示哪些行留下
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
# 布爾列表
list_bool = [False, False, True]
# 傳入布爾列表,只保留第3行'sidewinder'
df.loc[list_bool]
# ... max_speed shield
# ... sidewinder 7 8
示例8:用布爾運(yùn)算篩選行
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['移速', '護(hù)甲'])
# 篩選 '移速列' > 6 的行
df.loc[df['移速'] > 6]
# ... 移速 護(hù)甲
# ... sidewinder 7 8
# 篩選 '移速列' > 6 的行,同時(shí),只保留護(hù)甲列
df.loc[df['移速'] > 6,['護(hù)甲']] # 護(hù)甲加了方括號(hào),是為了以DataFrame顯示。
# ... 護(hù)甲
# ... sidewinder 8
# 用 & 表示 并
df.loc[(df['移速'] > 1) & (df['護(hù)甲'] < 8)]
# ... 移速 護(hù)甲
# ... viper 4 5
# 用 | 表示 或
df.loc[(df['移速'] > 4) | (df['護(hù)甲'] < 5)]
# ... 移速 護(hù)甲
# ... cobra 1 2
# ... sidewinder 7 8
示例9:使用 Callable
進(jìn)行篩選文章來源:http://www.zghlxwxcb.cn/news/detail-805789.html
- 1、lambda
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['移速', '護(hù)甲'])
# 使用lambda 篩選 護(hù)甲列 ==8 的行
df.loc[lambda df: df['護(hù)甲'] == 8]
# ... 移速 護(hù)甲
# ... sidewinder 7 8
- 2、自定義函數(shù)
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['移速', '護(hù)甲'])
# 定義篩選函數(shù)
def slect_df(df):
return df['護(hù)甲'] == 8
# 調(diào)用函數(shù)
df.loc[slect_df]
示例10:篩選后賦值,更改數(shù)據(jù)內(nèi)容文章來源地址http://www.zghlxwxcb.cn/news/detail-805789.html
import pandas as pd
# 構(gòu)建演示數(shù)據(jù)
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['移速', '護(hù)甲'])
# 篩選后,批量修改數(shù)據(jù)
df.loc[df['移速']>2] = 50
df
# ... 移速 護(hù)甲
# ... cobra 1 2
# ... viper 50 50
# ... sidewinder 50 50
# 篩選后,批量 + 30
df.loc[df['移速'] == 50] += 5
df
# ... 移速 護(hù)甲
# ... cobra 1 2
# ... viper 55 55
# ... sidewinder 55 55
到了這里,關(guān)于Pandas.DataFrame.loc[ ] 篩選數(shù)據(jù)-標(biāo)簽法 詳解 含代碼 含測(cè)試數(shù)據(jù)集 隨Pandas版本持續(xù)更新的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!