我有兩個有關Python Pandas數據框的索引相關問題。熊貓:按位置訪問索引更新和更改值
import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
'B' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'amount' : np.random.randn(8)})
df = df.ix[df.B != 'three'] # remove where B = three
df.index
>> Int64Index([0, 1, 2, 4, 6, 7], dtype=int64) # the original index is preserved.
1)我不明白爲什麼在我修改數據幀索引不會自動更新。有沒有辦法在修改數據框的同時自動更新索引?如果不是,那麼最有效的手動方法是什麼?
2)我希望能夠將df
的第5個元素的B
列設置爲'3'。但df.iloc[5]['B'] = 'three'
不這樣做。我檢查了manual,但它不包括如何更改按位置訪問的特定單元值。
如果我正在按行名訪問,我可以這樣做:df.loc[5,'B'] = 'three'
但我不知道索引訪問等價物是什麼。
P.S. Link1和link2是我第二個問題的相關答案。但是,他們不回答我的問題。
gr8!當我讀到這個問題時,我認爲我的答案更有意義! – Jeff