【问题标题】:Pandas get rows by its values from dataframesPandas 通过数据帧中的值获取行
【发布时间】:2018-09-26 17:43:38
【问题描述】:

我有一个参考数据框:

例如:

  time latitude longtitude pm2.5
  0 .  0        0          0
  1 .  0        5          1

  ......

我有一个疑问

例如:

  time latitude longtitude
  0 .  1        3
  1 .  0        5

  .......

我想得到与查询中的行匹配的 pm2.5。

我使用了行的迭代,但它似乎很慢。

predications_phy = []
for index, row in X_test.iterrows():    
    Y = phyDf[(phyDf["time"] == row["time"]) & (phyDf["latitude"] == row["latitude"]) & (phyDf["longtitude"] == row["longtitude"])]
    predications_phy.append(Y)

获取行的有效且正确的方法是什么?

【问题讨论】:

    标签: python python-3.x pandas scikit-learn


    【解决方案1】:

    给定参考数据框df1 和查询数据框df2,您可以执行左合并以提取结果:

    res = df2.merge(df1, how='left')
    
    print(res)
    
    #    time  latitude  longtitude  pm2.5
    # 0     0         1           3    NaN
    # 1     1         0           5    1.0
    

    除非您的操作无法向量化,否则强烈建议不要使用循环。

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 2016-03-18
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2015-03-26
      相关资源
      最近更新 更多