Python
 Computer >> コンピューター >  >> プログラミング >> Python

Python Pandas-要求されたラベルの整数の場所を取得し、完全に一致しない場合は以前のインデックス値を見つけます


要求されたラベルの整数位置を取得し、完全に一致しない場合は以前のインデックス値を見つけるには、 index.get_loc()を使用します 。パラメータメソッドを設定します 値ffill

まず、必要なライブラリをインポートします-

import pandas as pd

パンダインデックスの作成-

index = pd.Index([10, 20, 30, 40, 50, 60, 70])

パンダのインデックスを表示する-

print("Pandas Index...\n",index)

完全に一致するものがない場合は、前のインデックスの場所を取得します。値は、get_loc()の「method」パラメーターを使用して「ffill」に設定されます-

print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))

以下はコードです-

import pandas as pd

# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# get integer location from the given index
print("\nDisplay integer location from given index...\n",index.get_loc(20))
print("\nDisplay integer location from given index...\n",index.get_loc(50))

# Get the location of the previous index if no exact match
# The value is set "ffill" using the "method" parameter of the get_loc()
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))

出力

これにより、次の出力が生成されます-

Pandas Index...
Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

Number of elements in the index...
7

Display integer location from given index...
1

Display integer location from given index...
4

Get the location of the previous index if no exact match...
3

  1. Python Pandas –列の最大値を見つけて、対応する行の値を返します

    列の最大値を見つけて、パンダで対応する行の値を返すには、 df.loc [df [col] .idxmax()]を使用できます。 。それをよりよく理解するために例を見てみましょう。 ステップ 2次元で、サイズが変更可能で、潜在的に異種の表形式データdfを作成します。 入力DataFrame、dfを出力します。 変数colを初期化して、その列の最大値を見つけます。 df.loc [df [col] .idxmax()] を使用して、最大値とそれに対応する行を見つけます ステップ4の出力を印刷します。 例 import pandas as pd df = pd.DataFrame( &

  2. Pythonでプログラムを作成して、特定のシリーズのNaN値のインデックスを見つけます

    入力 − シリーズがあると仮定します 0    1.0 1    2.0 2    3.0 3    NaN 4    4.0 5    NaN 出力 − そして、NaNインデックスの結果は次のとおりです。 index is 3 index is 5 解決策 これを解決するには、以下の手順に従います- シリーズを定義します。 forループを作成してすべての要素にアクセスし、if条件を設定してisnan()をチェックします。最後に、インデックス位置を印刷