簡體   English   中英

Python Pandas-根據索引替換部分數據框列的值

[英]Python Pandas - Replacing values of a part of data frame column based on index

我正在根據其索引在Panda列中獲取特定值的首次出現,如下所示:

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

這將為我提供“ word1”或“ word2”首次出現的索引

然后,我要用新值替換記錄的舊值,直到確定的索引為止,如下所示:

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

這將用“ 5”替換直到數據幀的first_idx之前存在的所有“ 10”。 first_idx值之后的所有剩余的'10'將不被替換。

現在,我必須將first_idx值之后的所有'10'替換為'3'。 我通過計算數據幀的長度,然后用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)

但是還有其他更好/有效/簡單的方法來實現這一目標嗎?

從您使用的方式

df1.head(first_idx)

我認為您的索引是數字。 因此,一個簡單的

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

應該做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM