Python-基于索引替换部分数据帧列的值

Python-基于索引替换部分数据帧列的值,python,pandas,python-3.6,Python,Pandas,Python 3.6,我根据索引获取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”替换在数据帧的第一个

我根据索引获取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”替换在数据帧的第一个_idx之前存在的所有“10”。第一个_idx值之后剩余的所有“10”将不会被替换

现在我必须用'3'替换第一个_idx值之后出现的所有'10'。通过计算数据帧的长度,然后用第一个_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)

应该这样做

谢谢你@Eran。它起作用了。但是我用df1.loc尝试了同样的方法。它也做同样的工作。如果可能的话,你能解释一下两者之间的区别吗?因为两者都能获得相同的结果Sure@JKC。iloc用于实际行号。iloc[2:4]将对第2行和第3行进行切片,而不管它们的索引如何。loc使用数据帧的索引进行切片。它们可以是数字,也可以是非数字。如果您的索引是有序的数字(就像您的情况一样),那么两者的行为将完全相同。还可以阅读关于df.idx[]的内容,它将两者结合在一起。虽然我不怎么使用它,但我更喜欢loc和iloc的更明确的方式。