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

PythonPandas-条件がFalseのインデックス値を置き換えます


条件がFalseのインデックス値を置き換えるには、 index.isin()を使用します パンダのメソッド。まず、必要なライブラリをインポートします-

import pandas as pd

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

index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')

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

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

条件がFalseの値を置き換えます。ここでは、「装飾」を除いて、他のすべての要素が置き換えられます-

print("\nReplace index vales where condition is False...\n",index.where(index.isin(['Decor']), 'Miscellaneous'))

以下はコードです-

import pandas as pd

# Creating Pandas index
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')

# 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)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# replace values where condition is False
# Here, except the 'Decor', every other element gets replaced
print("\nReplace index vales where condition is False...\n",index.where(index.isin(['Decor']), 'Miscellaneous'))

出力

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

Pandas Index...
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')

Number of elements in the index...
5

The dtype object...
object

Replace index vales where condition is False...
Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous','Miscellaneous'],dtype='object', name='Products')

  1. Python-Pandasインデックスの最大値を返します

    パンダインデックスの最大値を返すには、 index.max()を使用します 方法。まず、必要なライブラリをインポートします- import pandas as pd パンダインデックスの作成 index = pd.Index([10, 20, 70, 40, 90, 50, 25, 30]) パンダのインデックスを表示する- print("Pandas Index...\n",index) 最大値を取得- print("\nMaximum value..\n", index.max()) 例 以下はコードです- import pandas a

  2. Python-DataFrameの値をPandasの別のDataFrameの値に置き換えます

    DataFrameの値を別のDataFrameの値に置き換えるには、replace()メソッドnPandasを使用します。 まず、最初にDataFrameを作成しましょう- dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini"], "Place": ["US", "UK"], "Units": [200, 500]}) 別のDataFrameを作成しましょう- dataFrame2 = pd.