Python Pandas - 返回使用掩碼設定的值的新索引


要返回使用掩碼設定的值的新索引,請在 Pandas 中使用 index.putmask() 方法。首先,匯入必要的庫——

import pandas as pd

建立 Pandas 索引——

index = pd.Index([5, 65, 10, 17, 75, 40])

顯示 Pandas 索引——

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

遮蔽並用值 111 放置索引值小於 3——

print("\nMask...\n",index.putmask(index < 30, 111))

示例

以下是程式碼——

import pandas as pd

# Creating Pandas index
index = pd.Index([5, 65, 10, 17, 75, 40])

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

# mask and place index values less than 3 with a value 111
print("\nMask...\n",index.putmask(index < 30, 111))

輸出

這將產生以下輸出——

Pandas Index...
Int64Index([5, 65, 10, 17, 75, 40], dtype='int64')

Number of elements in the index...
6

The dtype object...
int64

Mask...
Int64Index([111, 65, 111, 111, 75, 40], dtype='int64')

更新於: 13-Oct-2021

345 次觀看

開啟你的 職業生涯

完成課程認證

開始
廣告