【问题标题】:passing a filtered from list value to dataframe将过滤后的列表值传递给数据框
【发布时间】:2020-11-18 12:22:59
【问题描述】:

我想将列表中的值放入 df 列,条件取决于另一列。我试过了,但它抛出了ValueError:

terms = [0.02, 0.08, 0.24, 0.5, 1, 2]
df['col_1'] = max(list(filter(lambda x: x < df['col_2'], terms))) 

col_1 必须包含最接近col_2 的小于它的值。对于0.35,我想输入0.24

如何在没有循环的情况下实现这一点?

【问题讨论】:

    标签: python pandas dataframe filter


    【解决方案1】:

    这是merge_asof

    df = pd.DataFrame({'col_2':[0.35]})
    
    pd.merge_asof(df,pd.DataFrame({'col_1':terms}),
                  left_on='col_2',
                  right_on='col_1')
    

    输出:

       col_2  col_1
    0   0.35   0.24
    

    【讨论】:

    • 你用merge_asof解决了很多问题。我想知道它背后的思考过程是什么。这只是天才。 +1。
    猜你喜欢
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多