DataFrame.loc[]和DataFrame.iloc[]

DataFrame.loc專題學(xué)習(xí)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html?highlight=loc#pandas-dataframe-loc

Access a group of rows and columns by label(s) or a boolean array.
通過標(biāo)記或布爾數(shù)組獲取一組行列
.loc[] is primarily label based, but may also be used with a boolean array.
.loc[]主要是基于標(biāo)記的优妙,但也可以用布爾數(shù)組

Allowed inputs are:允許的輸入包括

A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).單個(gè)標(biāo)記嚣崭,例如5或‘a(chǎn)’妖枚,注意5會(huì)被解釋為一個(gè)索引的標(biāo)記签杈,而不會(huì)被認(rèn)為是一個(gè)整數(shù)位置

A list or array of labels, e.g. ['a', 'b', 'c'].一個(gè)標(biāo)簽組成的列表或數(shù)組 萌朱。

A slice object with labels, e.g. 'a':'f'.一個(gè)標(biāo)簽的切片
注意:與常規(guī)python不一樣的是废亭,loc的切片是兩端都包含的

A boolean array of the same length as the axis being sliced, e.g. [True, False, True].布爾數(shù)組

A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)一個(gè)可調(diào)用的函數(shù)

例子

創(chuàng)建一個(gè)dataframe
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
    index=['cobra', 'viper', 'sidewinder'],
    columns=['max_speed', 'shield'])
df
           max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8

單個(gè)標(biāo)簽进陡。注意返回的行是個(gè)series對(duì)象

df.loc['viper']
max_speed    4
shield       5
Name: viper, dtype: int64

通過一個(gè)標(biāo)簽列表. 使用 [[]] 返回一個(gè)dataframe亲铡、獲取對(duì)應(yīng)行

df.loc[['viper', 'sidewinder']]
            max_speed  shield
viper               4       5
sidewinder          7       8

通過一個(gè)行標(biāo)簽和一個(gè)列標(biāo)簽髓削,獲取對(duì)應(yīng)單個(gè)數(shù)據(jù)

df.loc['cobra', 'shield']
2

通過一個(gè)行標(biāo)簽的切片和單個(gè)列標(biāo)簽竹挡。獲取對(duì)應(yīng)行列

df.loc['cobra':'viper', 'max_speed']
cobra    1
viper    4
Name: max_speed, dtype: int64

通過與行軸長(zhǎng)度相同的布爾值列表、獲取行

df.loc[[False, False, True]]
            max_speed  shield
sidewinder          7       8

通過可以返回一個(gè)布爾值series對(duì)象的條件立膛,獲取行

df.loc[df['shield'] > 6]
            max_speed  shield
sidewinder          7       8

通過可以返回一個(gè)布爾值series對(duì)象的條件揪罕,并對(duì)列標(biāo)簽進(jìn)行指定

df.loc[df['shield'] > 6, ['max_speed']]
            max_speed
sidewinder          7

通過返回布爾series的可調(diào)用對(duì)象

df.loc[lambda df: df['shield'] == 8]
            max_speed  shield
sidewinder          7       8

設(shè)定值

對(duì)標(biāo)簽列表中所有匹配項(xiàng)設(shè)定值

df.loc[['viper', 'sidewinder'], ['shield']] = 50
df
            max_speed  shield
cobra               1       2
viper               4      50
sidewinder          7      50

對(duì)整行設(shè)定值

df.loc['cobra'] = 10
df
            max_speed  shield
cobra              10      10
viper               4      50
sidewinder          7      50

對(duì)整列設(shè)定值

df.loc[:, 'max_speed'] = 30
df
            max_speed  shield
cobra              30      10
viper              30      50
sidewinder         30      50

對(duì)可調(diào)用對(duì)象條件匹配的行設(shè)定值

df.loc[df['shield'] > 35] = 0
df
            max_speed  shield
cobra              30      10
viper               0       0
sidewinder          0       0

Getting values on a DataFrame with an index that has integer labels

獲取一個(gè)dataframe中具有整數(shù)標(biāo)簽作為索引的值

#Another example using integers for the index
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=[7, 8, 9], columns=['max_speed', 'shield'])
df
   max_speed  shield
7          1       2
8          4       5
9          7       8

用整數(shù)標(biāo)簽的切片獲取對(duì)應(yīng)行

df.loc[7:9]
   max_speed  shield
7          1       2
8          4       5
9          7       8

用復(fù)合索引獲取值

A number of examples using a DataFrame with a MultiIndex

#創(chuàng)建一個(gè)復(fù)合索引的dataframe
tuples = [
   ('cobra', 'mark i'), ('cobra', 'mark ii'),
   ('sidewinder', 'mark i'), ('sidewinder', 'mark ii'),
   ('viper', 'mark ii'), ('viper', 'mark iii')
]
index = pd.MultiIndex.from_tuples(tuples)
values = [[12, 2], [0, 4], [10, 20],
        [1, 4], [7, 1], [16, 36]]
df = pd.DataFrame(values, columns=['max_speed', 'shield'], index=index)
df
                     max_speed  shield
cobra      mark i           12       2
           mark ii           0       4
sidewinder mark i           10      20
           mark ii           1       4
viper      mark ii           7       1
           mark iii         16      36

單個(gè)標(biāo)簽梯码。返回的是具有單組標(biāo)簽的dataframe

df.loc['cobra']
         max_speed  shield
mark i          12       2
mark ii          0       4

通過單個(gè)索引的元組。Note this returns a Series.

df.loc[('cobra', 'mark ii')]
max_speed    0
shield       4
Name: (cobra, mark ii), dtype: int64

通過單個(gè)行列索引. Similar to passing in a tuple, this returns a Series.

df.loc['cobra', 'mark i']
max_speed    12
shield        2
Name: (cobra, mark i), dtype: int64

通過單個(gè)元組好啰。Note using [[]] returns a DataFrame.

df.loc[[('cobra', 'mark ii')]]
               max_speed  shield
cobra mark ii          0       4

單個(gè)元組的行索引及一個(gè)列標(biāo)簽

df.loc[('cobra', 'mark i'), 'shield']
2

從行索引元組至單個(gè)標(biāo)簽的切片

df.loc[('cobra', 'mark i'):'viper']
                     max_speed  shield
cobra      mark i           12       2
           mark ii           0       4
sidewinder mark i           10      20
           mark ii           1       4
viper      mark ii           7       1
           mark iii         16      36

元組索引至元組索引的切片

df.loc[('cobra', 'mark i'):('viper', 'mark ii')]
                    max_speed  shield
cobra      mark i          12       2
           mark ii          0       4
sidewinder mark i          10      20
           mark ii          1       4
viper      mark ii          7       1

DataFrame.iloc專題學(xué)習(xí)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html?highlight=iloc#pandas.DataFrame.iloc

Purely integer-location based indexing for selection by position.#純基于整數(shù)索引

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.#主要基于整數(shù)位置轩娶,也可以基于布爾值數(shù)組

Allowed inputs are:

An integer, e.g. 5.#一個(gè)整數(shù)

A list or array of integers, e.g. [4, 3, 0].#整數(shù)構(gòu)成的列表或數(shù)組

A slice object with ints, e.g. 1:7.#整型的切片對(duì)象

A boolean array.#一個(gè)布爾型數(shù)組

A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.#具有一個(gè)參數(shù)(調(diào)用series對(duì)象或dataframe對(duì)象)的可調(diào)用函數(shù),并返回上述其中一個(gè)用于索引的有效輸出框往。當(dāng)您沒有對(duì)調(diào)用對(duì)象的引用但希望基于某個(gè)值進(jìn)行選擇時(shí)鳄抒,這在方法鏈中很有用。

.iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics).

創(chuàng)建一個(gè)example

mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df = pd.DataFrame(mydict)
df
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

僅索引行

通過一個(gè)標(biāo)量整數(shù)

>>>type(df.iloc[0])
<class 'pandas.core.series.Series'>#獲得第[0]行椰弊,返回對(duì)象為Series
>>>df.iloc[0]
a    1
b    2
c    3
d    4
Name: 0, dtype: int64

通過一個(gè)整數(shù)組成的列表

df.iloc[[0]]
   a  b  c  d
0  1  2  3  4
type(df.iloc[[0]])
<class 'pandas.core.frame.DataFrame'>#獲得第[0]行许溅,返回對(duì)象為DataFrame
#返回第[0]和[1]行數(shù)據(jù)
df.iloc[[0, 1]]
     a    b    c    d
0    1    2    3    4
1  100  200  300  400

通過一個(gè)切片對(duì)象

#返回第[0]至[2]行
df.iloc[:3]
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

通過一個(gè)與行索引長(zhǎng)度一致的布爾值列表

df.iloc[[True, False, True]]
      a     b     c     d
0     1     2     3     4
2  1000  2000  3000  4000

通過一個(gè)可調(diào)用對(duì)象With a callable, useful in method chains. The x passed to the lambda is the DataFrame being sliced. This selects the rows whose index label even.

#返回偶數(shù)行
df.iloc[lambda x: x.index % 2 == 0]
      a     b     c     d
0     1     2     3     4
2  1000  2000  3000  4000

索引全部軸

You can mix the indexer types for the index and columns. Use : to select the entire axis.
可以將行和列的索引混合使用,以選擇全部軸的數(shù)據(jù)

通過標(biāo)量整數(shù)

df.iloc[0, 1]
2

通過整數(shù)列表

df.iloc[[0, 2], [1, 3]]
      b     d
0     2     4
2  2000  4000

通過切片對(duì)象

df.iloc[1:3, 0:3]
      a     b     c
1   100   200   300
2  1000  2000  3000

通過布爾值列表

df.iloc[:, [True, False, True, False]]
      a     c
0     1     3
1   100   300
2  1000  3000

With a callable function that expects the Series or DataFrame.
通過一個(gè)返回series或dataframe的可調(diào)用對(duì)象

df.iloc[:, lambda df: [0, 2]]
      a     c
0     1     3
1   100   300
2  1000  3000
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末秉版,一起剝皮案震驚了整個(gè)濱河市贤重,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌清焕,老刑警劉巖并蝗,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異秸妥,居然都是意外死亡滚停,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門粥惧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來铐刘,“玉大人,你說我怎么就攤上這事影晓×常” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵挂签,是天一觀的道長(zhǎng)疤祭。 經(jīng)常有香客問我,道長(zhǎng)饵婆,這世上最難降的妖魔是什么勺馆? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮侨核,結(jié)果婚禮上草穆,老公的妹妹穿的比我還像新娘。我一直安慰自己搓译,他們只是感情好悲柱,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著些己,像睡著了一般豌鸡。 火紅的嫁衣襯著肌膚如雪嘿般。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天涯冠,我揣著相機(jī)與錄音炉奴,去河邊找鬼。 笑死蛇更,一個(gè)胖子當(dāng)著我的面吹牛瞻赶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播派任,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼共耍,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了吨瞎?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤穆咐,失蹤者是張志新(化名)和其女友劉穎颤诀,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體对湃,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡崖叫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了拍柒。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片心傀。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖拆讯,靈堂內(nèi)的尸體忽然破棺而出脂男,到底是詐尸還是另有隱情,我是刑警寧澤种呐,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布宰翅,位于F島的核電站,受9級(jí)特大地震影響爽室,放射性物質(zhì)發(fā)生泄漏汁讼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一阔墩、第九天 我趴在偏房一處隱蔽的房頂上張望嘿架。 院中可真熱鬧,春花似錦啸箫、人聲如沸耸彪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搜囱。三九已至丑瞧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蜀肘,已是汗流浹背绊汹。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留扮宠,地道東北人西乖。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像坛增,于是被迫代替她去往敵國(guó)和親获雕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在python中收捣,眾所周知届案,數(shù)據(jù)預(yù)處理最好用的包就是pandas了,以下是pandas里的dataframe數(shù)據(jù)結(jié)...
    天涯海角醉云游閱讀 31,320評(píng)論 1 12
  • 本節(jié)中罢艾,我將介紹操作Series和DataFrame中的數(shù)據(jù)的基本手段楣颠。后續(xù)章節(jié)將更加深入地挖掘pandas在數(shù)據(jù)...
    米小河123閱讀 651評(píng)論 0 1
  • pandas入門 簡(jiǎn)介 pandas包含的數(shù)據(jù)結(jié)構(gòu)和操作工具能快速簡(jiǎn)單地清洗和分析數(shù)據(jù)。 pandas經(jīng)常與Num...
    python測(cè)試開發(fā)閱讀 2,388評(píng)論 1 16
  • 5.2 基本功能 本節(jié)中咐蚯,我將介紹操作Series和DataFrame中的數(shù)據(jù)的基本手段童漩。后續(xù)章節(jié)將更加深入地挖掘...
    漁家傲_俞閱讀 541評(píng)論 0 0
  • 早上起床就感覺不適,不知道是不是因?yàn)樽蛲砜尢啻悍妗:苊黠@的感覺到矫膨,對(duì)當(dāng)下失去了熱情,不想去做現(xiàn)在需要做的各種工作期奔,看...
    御風(fēng)而行_me閱讀 198評(píng)論 0 1