【问题标题】:If condition, store previous df column value, without loop如果条件,存储前一个df列值,不循环
【发布时间】:2022-10-07 19:11:43
【问题描述】:

是否可以在熊猫中不循环检索前一列值?

import pandas as pd
import numpy as np

df=pd.DataFrame({\'a\': [True, False, False, True, True, False], \'b\': [0, 0, 0, 3, 4, 4]})

df
Out[427]: 
       a  b
0   True  0
1  False  0
2  False  0
3   True  3
4   True  4
5  False  4
如果 df[\'a\'] = True,存储索引,否则存储前一个值
# Attempt 1
df[\'c\'] = np.where(df[\'a\'], df.index, df[\'c\'].shift(1))


# Attempt 2
df[\'c\'] = df.index
df[\'c\'] = np.where(df[\'a\'], df[\'c\'], df[\'c\'].shift(1))

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用ffill:

    df['b'] = df.index.to_series().where(df['a']).ffill(downcast='infer')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2022-01-25
      • 2020-06-25
      • 2021-10-20
      相关资源
      最近更新 更多