您好,登錄后才能下訂單哦!
iloc
是 pandas 庫(kù)中的一個(gè)屬性,用于基于整數(shù)位置的索引進(jìn)行數(shù)據(jù)選擇
以下是如何在 pandas 中使用 iloc
和 reset_index()
的示例:
import pandas as pd
# 創(chuàng)建一個(gè)簡(jiǎn)單的數(shù)據(jù)框
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# 顯示原始數(shù)據(jù)框
print("Original DataFrame:")
print(df)
# 使用 iloc 選擇數(shù)據(jù)
selected_data = df.iloc[[0, 2], [0, 1]] # 選擇第1行和第3行,第1列和第2列
print("\nSelected Data using iloc:")
print(selected_data)
# 重置索引
reset_df = df.reset_index(drop=True)
print("\nDataFrame after resetting index:")
print(reset_df)
# 在重置索引后使用 iloc 選擇數(shù)據(jù)
selected_data_after_reset = reset_df.iloc[[0, 2], [0, 1]]
print("\nSelected Data after resetting index:")
print(selected_data_after_reset)
輸出結(jié)果:
Original DataFrame:
A B
0 1 4
1 2 5
2 3 6
Selected Data using iloc:
A B
0 1 4
2 3 6
DataFrame after resetting index:
A B
0 1 4
1 2 5
2 3 6
Selected Data after resetting index:
A B
0 1 4
2 3 6
在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)簡(jiǎn)單的數(shù)據(jù)框。然后,我們使用 iloc
選擇了一些數(shù)據(jù)。接下來(lái),我們使用 reset_index()
函數(shù)重置了數(shù)據(jù)框的索引。最后,我們?cè)谥刂盟饕蟮臄?shù)據(jù)框上再次使用 iloc
選擇數(shù)據(jù)??梢钥吹?,iloc
在重置索引后的數(shù)據(jù)框上仍然有效。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。