Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。
Pandas Index.asof()
函數return從索引中返回標簽,如果不存在,則返回前一個。假定索引已排序,如果傳遞的索引標簽在索引中,則返回它;如果傳遞的索引不在索引中,則返回前一個索引標簽。
注意:該函數僅適用於排序的索引。如果未排序,則返回錯誤。
用法: Index.asof(label)
參數:
label:方法返回的標簽的最新索引標簽
返回:傳遞的標簽(如果在索引中)。如果傳遞的標簽不在排序索引中,則為前一個標簽;如果沒有這樣的標簽,則為NaN。
範例1:采用Index.asof()
函數返回最新的索引標簽,直到傳遞的索引標簽為止。
# importing pandas as pd
import pandas as pd
# Creating the Index
df = pd.Index([17, 69, 33, 15, 19, 74, 10, 5])
# Print the Index
df
輸出:
讓我們先對索引標簽進行排序
# sorting the index labels using the argsort() function
df = df[df.argsort()]
# Lets print the sorted index labels.
df
輸出:
現在,我們將在索引中找到最新的標簽,最多可顯示72個。
# find the latest index label upto 72
df.asof(72)
輸出:
正如我們在輸出中看到的那樣,該函數已返回69,因為它是小於72的前一個索引標簽。
範例2:采用Index.asof()
函數查找到給定日期的索引標簽。
# importing pandas as pd
import pandas as pd
# Creating the Index
idx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',
'2016-02-08', '2017-05-05'])
# Print the Index
df
輸出:
索引已按排序順序,因此我們將不對其進行排序。
現在我們將應用index.asof()
函數查找直到輸入標簽的索引標簽。
# to find the label in the index upto '2016-01-01'
idx.asof('2016-01-01')
輸出:
從輸出中可以看到,該函數已返回“ 2015-12-02”日期,該日期是索引中直到“ 2016-01-01”的上一個日期
相關用法
- Python pandas.map()用法及代碼示例
- Python Pandas Series.str.len()用法及代碼示例
- Python Pandas.factorize()用法及代碼示例
- Python Pandas TimedeltaIndex.name用法及代碼示例
- Python Pandas dataframe.ne()用法及代碼示例
- Python Pandas Series.between()用法及代碼示例
- Python Pandas DataFrame.where()用法及代碼示例
- Python Pandas Series.add()用法及代碼示例
- Python Pandas.pivot_table()用法及代碼示例
- Python Pandas Series.mod()用法及代碼示例
- Python Pandas Dataframe.at[ ]用法及代碼示例
- Python Pandas Dataframe.iat[ ]用法及代碼示例
- Python Pandas.pivot()用法及代碼示例
- Python Pandas dataframe.mul()用法及代碼示例
- Python Pandas.melt()用法及代碼示例
注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Index.asof()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。