2017-09-26 127 views
0

我提取基於其索引熊貓列的特定值的第一次出現的數據幀列的一部分的更換值,如下所示:Python的熊貓 - 基於索引

first_idx = df1.loc[df1.Column1.isin(['word1','word2'])].index.tolist()[0] 

這會給我是「字1」或「單詞2」中第一次出現的索引

然後我更換如下圖所示的記錄,直到用新值所確定的指數舊值:

df1.head(first_idx)['Column1'].replace({'10': '5'}, inplace=True) 

這將取代所有'10',直到數據幀的first_idx爲'5'。 first_idx值後的所有剩餘'10將不會被替換。

現在我必須用'3'替換first_idx值後的所有'10'。我已經通過計算數據幀的長度然後用first_idx值減去它來嘗試以下內容。

len(df1)       # This will show the actual length/total number of records of a dataframe column. 
temp = (len(df1)-first_idx)-1 # This will determine the remaining count of records barring the count of records until first_idx value. 
df1.tail(temp)     # This will show all records that are present after the first_idx value. 
df1.tail(temp)['Column1'].replace({'10': '3'}, inplace=True) 

但是有沒有其他更好/有效/簡單的方法來實現相同?

回答

1

從你的方式使用

df1.head(first_idx) 

我假設你的指數數值。因此,一個簡單的

df1.iloc[first_idx + 1:, :]['Column1'].replace({'10': '3'}, inplace=True) 

應該做的。

+0

謝謝@Eran。有用。但是我對df1.loc也是這樣。它也做同樣的工作。如果可能的話,請你解釋兩者之間有什麼區別,因爲它們都達到相同的結果 – JKC

+0

當然@JKC。 iloc用於實際行號。無論索引如何,df1.iloc [2:4]都會對第2行和第3行進行分片。使用數據幀的索引來定位切片。他們可以是數字或非數字。如果您的指數是有序數字(就像您的情況一樣),兩者的表現完全相同。另請閱讀關於將兩者結合的df.idx []。雖然我沒有多用它,但我更喜歡loc和iloc的更明確的方式。 – Eran