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

Python Pandas-インデクサーを計算し、完全に一致するものがない場合は最も近いインデックス値を見つけます


インデクサーを計算し、完全に一致しない場合に最も近いインデックス値を見つけるには、 index.get_indexer()を使用します 方法。 メソッドも設定します 最も近いへのパラメータ 。

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

import pandas as pd

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

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

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

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

「get_indexer」を使用してインデクサーとマスクを計算します。「method」パラメーターを使用して完全に一致するものがない場合は、最も近いインデックス値を見つけます。値は「最も近い」に設定されます-

print("\nGet the indexes...\n",index.get_indexer([30, 25, 58, 50, 69], method="nearest"))

以下はコードです-

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)

# Compute indexer and mask using the "get_indexer"
# Find the nearest index value if no exact match using the "method" parameter.
# The value is set "nearest"
print("\nGet the indexes...\n",index.get_indexer([30, 25, 58, 50, 69], method="nearest"))

出力

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

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

Number of elements in the index...
7

Get the indexes...
[2 2 5 4 6]

  1. Pythonでパンダのバージョンとその依存関係を見つける

    Pandasは、Pythonでのデータ分析のための重要なパッケージです。パンダにはさまざまなバージョンがあります。バージョンの不一致により、問題が発生する場合があります。したがって、パンダのバージョン番号を見つける必要があります。次のコードを使用して簡単に確認できます。 以下のようなコマンドを使用して、バージョンを取得できます- pandas.__version__ 例 >>> import pandas as pd >>> print(pd.__version__) 0.25.2 >>> 以下のような関数を使用して、依存関係のバージョ

  2. Python正規表現で各一致の正確な位置を見つけるにはどうすればよいですか?

    re.finditer()メソッドを使用して、Python正規表現を使用して特定の文字列内の各一致の正確な位置を検索します 例 import re p = re.compile("[A-Z0-9]") for m in p.finditer('A5B6C7D8'):     print m.start(), m.group() 出力 これにより、出力が得られます 0 A 1 5 2 B 3 6 4 C 5 7 6 D 7 8