代码之家  ›  专栏  ›  技术社区  ›  konichiwa

从pandas中当前行列与下一行列的比较中获取最小日期值

  •  0
  • konichiwa  · 技术社区  · 6 年前

    enter image description here

    我有一个熊猫DF有3列: col1 , col2 , col3 . 在某些情况下,第1列和第3列中的值可能为空。柱 COL2 开始是空的。目标是填充 COL2 . 我想迭代每一行来比较每一行 COL3 当前行的值 COL1 在下一排。 COL2 应该成为最小的日期值(如图中所示)。

    我怎样才能在熊猫身上做到这一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   ALollz    6 年前

    使用 np.min 具有 shift

    样本数据

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'col1': ['2013-12-19', '2014-12-16', '2015-02-06', '2016-01-22', 
                                '2016-02-24', '2016-04-25', '2017-04-13'],
                       'col3': ['2014-06-28', '2015-10-07', '2015-07-19', '2016-02-11', 
                                '2016-04-28', '2017-02-28', '2018-02-15']})
    df = df.apply(pd.to_datetime)
    

    代码

    df['col2'] = np.min([df.col1.shift(-1).values, df.col3.values], axis=0)
    

    产量 df :

            col1       col3       col2
    0 2013-12-19 2014-06-28 2014-06-28
    1 2014-12-16 2015-10-07 2015-02-06
    2 2015-02-06 2015-07-19 2015-07-19
    3 2016-01-22 2016-02-11 2016-02-11
    4 2016-02-24 2016-04-28 2016-04-25
    5 2016-04-25 2017-02-28 2017-02-28
    6 2017-04-13 2018-02-15 2018-02-15
    
        2
  •  0
  •   atlas    6 年前

    抱歉…我误解了你的问题。我承认我略读了—对不起!

    这应该管用…

    for idx in range(len(df)-1):
        df.loc[idx, 'col2'] = min(df.loc[idx, 'col3'], df.loc[idx+1, 'col1'])
    

    这将保留最后一个值 col2 作为 nan 由于偏移迭代。

    如果有帮助请告诉我!