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

PythonPandasCategoricalIndex-カテゴリの名前を変更


カテゴリの名前を変更するには、CategoricalIndex rename_categories()を使用します パンダのメソッド。まず、必要なライブラリをインポートします-

import pandas as pd

CategoricalIndexは、限られた数の、通常は固定された数の可能な値のみを取ることができます。 「categories」パラメータを使用して、カテゴリのカテゴリを設定します。 「ordered」パラメータを使用して、カテゴリを順序どおりに扱います-

catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

カテゴリの名前を変更します。古いカテゴリを置き換える新しいカテゴリを設定します-

print("\nCategoricalIndex after renaming categories...\n",catIndex.rename_categories([5, 10, 15, 20]))

以下はコードです-

import pandas as pd

# CategoricalIndex can only take on a limited, and usually fixed, number of possible values
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the CategoricalIndex
print("CategoricalIndex...\n",catIndex)

# Get the categories
print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Rename categories
# Set the new categories that will replace the old categories
print("\nCategoricalIndex after renaming categories...\n",catIndex.rename_categories([5, 10, 15, 20]))

出力

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

CategoricalIndex...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

DisplayingCategories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')

CategoricalIndex after renaming categories...
CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')

  1. Pythonでのタイムスタンプの比較–パンダ

    タイムスタンプを比較するために、インデックス演算子、つまり角かっこを使用できます。まず、必要なライブラリをインポートします- import pandas as pd 3列のデータフレームを作成する- dataFrame = pd.DataFrame(    {       "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],       &

  2. Python – Pandas Dataframe.rename()

    PandasでDataFrame列名の名前を変更するのは非常に簡単です。あなたがする必要があるのはrename()を使うことだけです メソッドを実行し、変更する列名と新しい列名を渡します。例を見て、それがどのように行われるかを見てみましょう。 ステップ 2次元、サイズ変更可能、潜在的に異種の表形式データ、 dfを作成します 。 入力DataFrame、 dfを印刷します 。 rename()を使用します 列名の名前を変更するメソッド。ここでは、列「x」の名前を新しい名前 new_xに変更します。 。 名前が変更された列を使用してDataFrameを印刷します。 例 import p