简体   繁体   English

Python Pandas-根据索引替换部分数据框列的值

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

I am fetching the first occurrence of a particular value in a Panda column based on its index as shown below : 我正在根据其索引在Panda列中获取特定值的首次出现,如下所示:

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

This will give me the index of first occurrence of either 'word1' or 'word2' 这将为我提供“ word1”或“ word2”首次出现的索引

Then I am replacing old values of the records until the determined index with new values as shown below : 然后,我要用新值替换记录的旧值,直到确定的索引为止,如下所示:

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

This will replace all '10's that are present until the first_idx of the dataframe with '5's. 这将用“ 5”替换直到数据帧的first_idx之前存在的所有“ 10”。 All the remaining '10's present after the first_idx value will not be replaced. first_idx值之后的所有剩余的'10'将不被替换。

Now I have to replace all '10's present after the first_idx value with '3's. 现在,我必须将first_idx值之后的所有'10'替换为'3'。 I have tried the below by calculating the length of data frame and then subtracting it with the first_idx value. 我通过计算数据帧的长度,然后用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)

But is there any other better / efficient / simple way to achieve the same ? 但是还有其他更好/有效/简单的方法来实现这一目标吗?

From the way you used 从您使用的方式

df1.head(first_idx)

I assume your indices are numeric. 我认为您的索引是数字。 Thus, a simple 因此,一个简单的

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

Should do. 应该做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM