python - 在 pandas 中的某一行之前设置行而不进行迭代

标签 python pandas dataframe vectorization

我在 pandas 数据框中有一列,我想将“大”之前的“正常”的任何不间断序列更改为“大”。我不想将列中“正常”的所有实例替换为“大”。比如我想把下面的左栏改为右栏:

<表类=“s-表”> <标题> 输入 结果 <正文> 小 小 小 小 正常 正常 小 小 正常 正常 小 小 正常

这对于迭代来说很简单:

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

然而,这是低效的。有没有一种简洁的矢量化方法来做到这一点?

最佳答案

尝试将 bfillwhere 一起使用:

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/

相关文章:

python - 如果字典键是任何其他键中的子字符串,则将其删除

python - 使用 Sympy 在 python 中进行微分

python - 以可以在 Python 中排序的格式存储输出

python - 在保持数据框的同时选择列中的第二个(或第 n 个)最小值

python - 分隔行 python pandas

python - 根据 pandas 中一列的值从行创建列

r - 无法使用 R 将 Inf 替换为 dplyr 链中的自定义值

python - 扩展 NLP 实体提取

python - 仅将选定的列转换为使用熔化和枢轴转置?

Python Pandas Dataframe 条件 If、Elif、Else