pandas.DataFrame()中的iloc和loc用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/missyougoon/article/details/83375375

简单的说:
iloc,即index locate 用index索引进行定位,所以参数是整型,如:df.iloc[10:20, 3:5]
loc,则可以使用column名和index名进行定位,如:
df.loc[‘image1’:‘image10’, ‘age’:‘score’]
实例:

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

np.random.seed(666)

df = pd.DataFrame(np.random.rand(25).reshape([5, 5]), index=['A', 'B', 'D', 'E', 'F'], columns=['c1', 'c2', 'c3', 'c4', 'c5'])

print(df.shape) # (5, 5)

# 返回前五行
df.head()
# 返回后五行
df.tail()

# 访问 某几个 列
print(df[['c1', 'c4']])
'''
         c1        c4
A  0.700437  0.727858
B  0.012703  0.099929
D  0.200248  0.700845
E  0.774479  0.110954
F  0.023236  0.197503
'''

# 赋值于一个新的 dataframe
sub_df = df[['c1', 'c3', 'c5']]
'''
         c1        c3        c5
A  0.700437  0.676514  0.951458
B  0.012703  0.048813  0.508066
D  0.200248  0.192892  0.293228
E  0.774479  0.112858  0.247668
F  0.023236  0.340035  0.909180
'''

# 查看前五行
print(sub_df.head(5))
'''
         c1        c3        c5
A  0.700437  0.676514  0.951458
B  0.012703  0.048813  0.508066
D  0.200248  0.192892  0.293228
E  0.774479  0.112858  0.247668
F  0.023236  0.340035  0.909180
'''

# 查看中间 几行 的数据 使用 方法 iloc
print(sub_df.iloc[1:3, :])  # iloc : index location  用索引定位
'''
         c1        c3        c5
B  0.012703  0.048813  0.508066
D  0.200248  0.192892  0.293228
'''

# 过滤 列
print(sub_df.iloc[1:2, 0:2]) # 和python的用法一样,但是 该方法 是 基于 index 信息的
'''
         c1        c3
B  0.012703  0.048813
'''

# loc 方法, 通过label 名称来过滤
print(sub_df.loc['A':'B', 'c1':'c3']) # 基于 label 选择
'''
         c1        c3
A  0.700437  0.676514
B  0.012703  0.048813
'''

需要注意的是:
在iloc使用索引定位的时候,因为是索引,所以,会按照索引的规则取值,如:[1:5] 会取出 1,2,3,4 这4个值。
但是loc按照label标签取值则不是这样的。如:[‘A’:‘C’] A,B,C 都会取出来。

猜你喜欢

转载自blog.csdn.net/missyougoon/article/details/83375375