【问题标题】:Pandas Iterrows: Faster Alternatives? [duplicate]Pandas Iterrows:更快的选择? [复制]
【发布时间】:2021-09-25 00:39:37
【问题描述】:

我正在尝试加快我的一项功能。我已经读到“矢量化”是在 Pandas 中运行这些类型操作的最快方法,但是如何使用此代码实现这一点(或其他更快的方法):

虚拟数据

a = pd.DataFrame({'var1' : [33, 75, 464, 88, 34], 'imp_flag' : [1, 0, 0, 1, 1], 'donor_index' : [3, np.nan, np.nan, 4, 0]})

>>> a
   var1  imp_flag  donor_index
0    33         1          3.0
1    75         0          NaN
2   464         0          NaN
3    88         1          4.0
4    34         1          0.0

有问题的操作

for index, row in a[a['imp_flag'] == 1].iterrows():
    new_row = a[a.index == row.donor_index]
    b = b.append(new_row)

预期输出

>>> b
   var1  imp_flag  donor_index
1    75         0          NaN
1    75         0          NaN
2   464         0          NaN

【问题讨论】:

  • 您提供的输出与您的代码返回不匹配。这是预期的吗?你能澄清一下这个问题吗?

标签: python pandas performance numpy


【解决方案1】:

有几件事我不明白

如果您在创建 a

a = pd.DataFrame({'var1' : [33, 75, 464, 88, 34], 'imp_flag' : [1, 0, 0, 1, 1], 'donor_index' : [3, 1, 2, 4, 0]})

>>> a
   var1  imp_flag  donor_index
0    33         1            3
1    75         0            1
2   464         0            2
3    88         1            4
4    34         1            0

您确定在您的示例中选择a[a['imp_flag'] == 1] 是正确的吗?看来你在 b 上得到结果的方式是相反的a[a['imp_flag'] == 0]

那么,你真的需要dataFrame b中的重复值吗?

我的解决方案如下:

idxs = a[a.imp_flag == 0].donor_index
b = a.iloc[idxs]
# or in one-line b = a.iloc[a[a.imp_flag == 0].donor_index]

>>> b
   var1  imp_flag  donor_index
1    75         0            1
2   464         0            2

【讨论】:

    【解决方案2】:

    IIUC,如果 imp_flag 等于 1,您想要子选择行

    您可以简单地使用query 来匹配相关行:

    b = a.loc[a.query('imp_flag == 1')['donor_index']]
    

    或者,您可以index and select your data 使用:

    b = a.loc[a[a['imp_flag'] == 1]['donor_index']]
    

    输出:

       var1  imp_flag  donor_index
    3    88         1            4
    4    34         1            0
    0    33         1            3
    

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 2018-12-11
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 2016-04-17
      • 2019-04-14
      • 1970-01-01
      • 2010-09-11
      相关资源
      最近更新 更多