簡體   English   中英

Pandas dataframe:pandas索引get_loc的正確用法是什么?

[英]Pandas dataframe: what is the correct use of pandas index get_loc?

我在get_loc的文檔中看到它返回:

如果是唯一索引則為 int,如果為單調索引則為 slice,否則為 mask

訪問 dataframe 時,您使用什么索引方法使用此返回類型? ilocloc[]

它與DataFrame.iloc一起使用,因為它由 label 返回 position。

例如,如果需要b列的第三個值,則需要返回b的 position ,然后使用Index.get_loc

df = pd.DataFrame({'a':[1,2,3],
                   'b':[2,3,4]}, index=list('abc'))


print (df.columns.get_loc('b'))
1

out = df.iloc[2, df.columns.get_loc('b')]
print (out)
4

所以像這樣工作:

out = df.iloc[2, 1]
print (out)
4

處理列表中多個值的類似方法是Index.get_indexer

print (df.columns.get_indexer(['b', 'a']))
[1 0]

out = df.iloc[2, df.columns.get_indexer(['b', 'a'])]
print (out)
b    4
a    3
Name: c, dtype: int64

out = df.iloc[2, [1, 0]]
print (out)
b    4
a    3
Name: c, dtype: int64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM