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)
但是有没有其他更好/有效/简单的方法来实现相同?
谢谢@Eran。有用。但是我对df1.loc也是这样。它也做同样的工作。如果可能的话,请你解释两者之间有什么区别,因为它们都达到相同的结果 – JKC
当然@JKC。 iloc用于实际行号。无论索引如何,df1.iloc [2:4]都会对第2行和第3行进行分片。使用数据帧的索引来定位切片。他们可以是数字或非数字。如果您的指数是有序数字(就像您的情况一样),两者的表现完全相同。另请阅读关于将两者结合的df.idx []。虽然我没有多用它,但我更喜欢loc和iloc的更明确的方式。 – Eran