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)
这会将数据帧 first_idx 之前的所有“10”替换为“5”。 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)
应该做的。
我正在根据其索引在 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)
这会将数据帧 first_idx 之前的所有“10”替换为“5”。 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)
应该做的。