pandas中loc和iloc

先随机生成一个DataFrame:

import numpy as np
import pandas as pd

# 随机生成4*4矩阵
metrix = np.random.randint(1, 20, (4,4))
df = pd.DataFrame(metrix, index=['a', 'b', 'c', 'd'], columns=['A', 'B', 'C', 'D'])
print(df)
------------------
     A   B   C   D
a  10  16  10  15
b  10   7   6  14
c  14   5  16   7
d  11  16  14   8

如果要查找列,可以用df['A']来表示。

如果要针对行操作,则可以使用iloc和loc这两个方法。

loc表示location,通过DataFrame的index来确认位置,且进行切片时为左右闭区间;iloc为integer location,通过行号来索引,左闭右开区间。

loc方法:

# 对行根据index切片
print(df.loc['a':'c'])
------------------
    A   B   C   D
a  10  16  10  15
b  10   7   6  14
c  14   5  16   7
------------------

# 同时也可以对列根据columns切片
print(df.loc['a':'c', 'A':'C'])
------------------
    A   B   C
a  10  16  10
b  10   7   6
c  14   5  16

iloc方法:

# 对行根据行号切片
print(df.loc[0:2])
------------------
    A   B   C   D
a  10  16  10  15
b  10   7   6  14
------------------

# 同时也可以对列根据列号切片
print(df.loc[0:2, 0:4])
------------------
    A   B   C   D
a  10  16  10  15
b  10   7   6  14
原文地址:https://www.cnblogs.com/bzsszhao/p/13320926.html