【问题标题】:pandas dataframe comparing previous rows with conditions熊猫数据框将前几行与条件进行比较
【发布时间】:2022-12-13 04:06:06
【问题描述】:

Python 和 Pandas 新手在这里。我有以下数据框,我希望能够比较前一行/多行中路由和 vals 相同的行,并相应地更新 frm 和 to。

DF:
   route  frm    to  val
0      1    0   100    3
1      1  100   300    2
2      1  300   500    3
3      1  500  9999    3
4      2    0   100    3
5      2  100   300    3
6      2  300   500    3
7      2  500  9999    3
Desired Output:
   route  frm    to  val
0      1    0   100    3
1      1  100   300    2
3      1  300  9999    3
7      2  0    9999    3

我已经使用 shift() 尝试了以下方法,这让我完成了一部分,但我不确定如何获得所需输出的最佳方法。

任何建议,将不胜感激。

df['f'] = np.where((df.route.eq(df.route.shift())) & (df.val == df.val.shift()),df.frm.shift(),df.frm)
df['t'] = np.where((df.route.eq(df.route.shift())) & (df.val == df.val.shift()),df.to.shift(),df.to)
Output:

   route  frm    to  val    f    t
0      1    0   100    3    0  100
1      1  100   300    2  100  300
2      1  300   500    3  300  500
3      1  500  9999    3  300  500
4      2    0   100    3    0  100
5      2  100   300    3    0  100
6      2  300   500    3  100  300
7      2  500  9999    3  300  500

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:
    # define custom function to compare rows and update frm and to
    def update_frm_to(row):
        # if route and val are the same in the previous row, update frm and to
        if row.route == row.route.shift() and row.val == row.val.shift():
            row.frm = row.frm.shift()
            row.to = row.to.shift()
        return row
    
    # apply the custom function to each row of the DataFrame
    df = df.apply(update_frm_to, axis=1)
    

    这将更新每一行中的 frm 和 to 列,其中 route 和 val 值与前一行相同。

    然后,您可以使用 drop_duplicates() 方法删除任何重复的行

    # remove duplicate rows
    df = df.drop_duplicates()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多