【问题标题】:How to iter throw rows in pandas and compare with the rest of the dataframe如何遍历 pandas 中的行并与数据框的其余部分进行比较
【发布时间】:2018-07-10 22:02:42
【问题描述】:

我有一个如下所示的数据框,其中包含航班搜索结果的数据

search_id  total_fare  changes_airport
abc        101         False
abc        121         True
abc        105         True
abd        120         True

现在我想添加一个名为“alternatives”的列,如果有另一行,则每行返回 True:

  • 相同的search_id

  • total_fare 相差不到 10

  • changes_airport == False

我正在尝试类似:

for index, row in df.iterrows():
    df.loc[row,'alternatives']=bool(dfs[(df.changes_airport==False)&_
    (df.search_id==row['search_id'])&_
    (df.total_fare<row['total_fare']+10)].shape[0])

我发现困难的是遍历行并同时分析数据帧的其余部分。

我想知道正确的语法,或许还有更有效的执行方式。

谢谢!

【问题讨论】:

  • total_fare差异小于10是什么意思?您还可以发布上述示例 df 的预期输出吗?
  • 第三行应该返回 True,因为还有另一行(第 1 行)具有相同的 search_id、changes_airport==False 并且 105-101 小于 10

标签: python pandas loops iteration


【解决方案1】:

这是一种假设原始数据框名为 df 的解决方案:

import pandas as pd

# Group by id and find minimum value
df1 = df.groupby('search_id').min()

# Keep only id with changes_airport == False
df1 = df1[df1['changes_airport'] == False].reset_index()

# Merge the two data frames - creates additional columns in df2
df2 = pd.merge(df, df1, how='outer', on=['search_id'])

# Fill the new column based on the difference between current cell total_fare 
# and the minimum fare for the respective search_id
df2['alternatives'] = (df2['total_fare_x'] - df2['total_fare_y']) < 10

# Drop auxiliary columns
del df2['changes_airport_y'], df2['total_fare_y']

print(df2)

   changes_airport_x search_id  total_fare_x  alternatives
0              False       abc           101          True
1               True       abc           121         False
2               True       abc           105          True
3               True       abd           120         False

【讨论】:

  • 好的,很好。我只会颠倒前两个步骤。
  • 只是为了运动,有没有办法用 transform、np.where 或 iterrows... 来执行相同的任务?
  • 问题的棘手部分是列中单元格的值是根据不同行和列中另一个单元格中的值确定的。我不确定使用您列出的命令是否很简单。另一个问题是速度。 iterrows 逐行应用该函数,并且一定会更慢。如果我不能直接分配单元格值,我个人会坚持加入。它们非常强大。
  • 好的,非常感谢!!
最近更新 更多