pandas-03 DataFrame()中的iloc和loc用法


pandas-03 DataFrame()中的iloc和loc用法

簡單的說:
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
'''


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM