我在 pandas 数据框中有一列,我想将“大”之前的“正常”的任何不间断序列更改为“大”。我不想将列中“正常”的所有实例替换为“大”。比如我想把下面的左栏改为右栏:
这对于迭代来说很简单:
for i, v in df['input'].iterrows():
if v == 'large':
index = i
while df['input'].iloc(index-1) == 'normal':
df['input'].iloc(index-1) = 'large'
index -= 1
然而,这是低效的。有没有一种简洁的矢量化方法来做到这一点?
最佳答案
尝试将 bfill
与 where
一起使用:
df1.loc[df1['input'].eq("normal")] = np.nan
df1['result'] = df1.fillna(method='bfill').where(df1.notnull() | (df1.shift(-1) != 'small')).fillna('normal')
df1:
input result
0 small small
1 small small
2 NaN large
3 NaN large
4 large large
5 small small
6 NaN normal
7 small small
8 NaN large
9 large large
关于python - 在 pandas 中的某一行之前设置行而不进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65936880/