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

Python Pandas-2つのIndexオブジェクトの共通部分を形成し、結果を並べ替えます


2つのIndexオブジェクトの交差を形成するには、 index1.intersection(index2)を使用します パンダのメソッド。結果を並べ替えるには、並べ替えを使用します パラメータ。

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

import pandas as pd

パンダindex1とindex2の作成-

index1 = pd.Index([4, 3, 2, 1])
index2 = pd.Index([8, 2, 6, 4])

パンダのインデックス1とインデックス2を表示する

print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)

交差点を実行します。結果は「sort」パラメータを使用してソートされます

res = index1.intersection(index2, sort=None)

以下はコードです-

import pandas as pd

# Creating Pandas index1 and index2
index1 = pd.Index([4, 3, 2, 1])
index2 = pd.Index([8, 2, 6, 4])

# Display the Pandas index1 and index2
print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)

# Return the number of elements in Index1 and Index2
print("\nNumber of elements in index1...\n",index1.size)
print("\nNumber of elements in index2...\n",index2.size)

# Perform intersection
# The results are sorted using the "sort" parameter
res = index1.intersection(index2, sort=None)

# Intersection of both the indexes and returning sorted result
print("\nThe index1 and index2 intersection (sorted result)...\n",res)

出力

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

Pandas Index1...
Int64Index([4, 3, 2, 1], dtype='int64')
Pandas Index2...
Int64Index([8, 2, 6, 4], dtype='int64')

Number of elements in index1...
4

Number of elements in index2...
4

The index1 and index2 intersection (sorted result)...
Int64Index([2, 4], dtype='int64')

  1. Python-2つの文字列の共通部分

    この記事では、2つの弦を異なる方法で交差させる方法を学びます。 以下の手順に従って問題を解決してください。 2つの文字列と空の文字列を初期化します。 最初の文字列を繰り返し処理し、現在の文字が2番目の文字列にも存在し、新しい文字列にまだ存在しない場合は、新しい文字列に追加します。 結果を印刷します。 例 # initializing the string string_1 = 'tutorialspoint' string_2 = 'tut' result = '' # finding the common chars from bot

  2. Pythonでの2つの配列の共通部分(ラムダ式とフィルター関数)

    この記事では、Lambda式とフィルター関数を使用してPythonで2つの配列が交差することについて学習します。 問題は、2つの配列が与えられ、両方の共通要素を見つける必要があることです。 アルゴリズム 1. Declaring an intersection function with two arguments. 2. Now we use the lambda expression to create an inline function for selection of elements with the help of filter function checking that e