【问题标题】:Pandas/Python check value in between and output value form another columnPandas/Python 检查中间值和另一列的输出值
【发布时间】:2021-03-19 09:00:48
【问题描述】:

我有以下数据框和一个等于20 的变量。我需要找到该变量在 col2 中的位置(此处介于 10 和 50 之间)并输出 col1 中的最小值,此处为 2。另一个示例是变量等于 51,col1 的正确输出将是3

我可以使用 if 公式来解决,但我希望为更大的数据集找到更好的解决方案。

d = {'col1': [1, 2, 3, 4, 5], 'col2': [0, 10, 50, 60, 70]}
df = pd.DataFrame(data=d)

【问题讨论】:

    标签: python pandas dataframe between


    【解决方案1】:

    boolean indexingDataFrame.loc 一起使用,然后通过Series.iat 获取col1 列的最后一个值:

    a = df.loc[df['col2'] <= 20, 'col1'].iat[-1]
    print (a)
    2
    a = df.loc[df['col2'] <= 51, 'col1'].iat[-1]
    print (a)
    3
    a = df.loc[df['col2'] <= 10, 'col1'].iat[-1]
    print (a)
    2
    

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多