【问题标题】:Pandas - apply & lambda with a condition and input from a functionPandas - 使用条件和函数输入的应用和 lambda
【发布时间】:2020-03-10 14:36:41
【问题描述】:

下面的伪代码需要使用 lambda & apply。我对实现它的 else 部分感到震惊,并在 DF 上循环并在遇到更多语法问题时创建一个新的。

提前致谢。

DataFrame [df]
a    b    c   d    e    f
100  10   1   www  qqq  1/1/2020
200  20   2   eee  rrr  2/1/2020
300  30   3   ttt  yyy  3/1/2020
400  40   4   uuu  iii  4/1/2020
500  50   5   ooo  ppp  5/1/2020 

def func(x,y):
   for i, r in df.iterrows():
      df_new = df[df['a'].isin(x)]
      if df['b'] <= y:
         df_new['newcolumn1'] = df['b']
         df_new['newcolumn2'] = df['c']
         df_new['newcolumn3'] = df['d']
         df_new['newcolumn4'] = df['e']
         df_new['newcolumn5'] = df['f']
         df_new['newcolumn6'] = y - df['b']
      else:
         continue 
 return df;

【问题讨论】:

    标签: python pandas lambda apply


    【解决方案1】:

    你没有理由在这里使用任何显式循环或apply

    def func(x, y):
        df_new = df[df['a'].isin(x)]
        df2 = df_new.loc[df_new['b'] <= y, df.columns[1:]]
        df2.columns = ['newcolumn' + str(i) for i in range(1,6)]
        df2['newcolumn6'] = y - df_new['b']
        df2 = df2.astype('object')    # avoid conversion of int to float with NaN
        return pd.concat([df_new, df2], axis=1)
    

    演示:

    func([100, 300], 25)
    

    给予:

         a   b  c    d    e         f newcolumn1 newcolumn2 newcolumn3 newcolumn4 newcolumn5 newcolumn6
    0  100  10  1  www  qqq  1/1/2020         10          1        www        qqq   1/1/2020         15
    2  300  30  3  ttt  yyy  3/1/2020        NaN        NaN        NaN        NaN        NaN        NaN
    

    【讨论】:

    • 谢谢。将检查逻辑,一百万行的性能如何?
    • 这将取决于计算机的性能 ;-) ... 更严重的是,这将需要一些时间,但由于一切都是完全矢量化的,远远低于任何基于 applyiterrows 的方式。
    【解决方案2】:
    y=20
    new_df = df[df['b'] >= y]
    new_df['newcolumn6'] = new_df['b'].apply(lambda x: y-x)
    

    输出

         a   b  c    d    e         f  newcolumn6
    1  200  20  2  eee  rrr  2/1/2020           0
    2  300  30  3  ttt  yyy  3/1/2020         -10
    3  400  40  4  uuu  iii  4/1/2020         -20
    4  500  50  5  ooo  ppp  5/1/2020         -30
    

    【讨论】:

    • 我没有理由看到在这里使用apply,为什么不只是new_df['newcolumn6'] = new_df['b']-y
    • 我相信他会选择 y-b,而不是 b-y
    • 对,然后是new_df['newcolumn6'] = y-new_df['b'];它仍然是矢量化的,而不是像 apply 那样迭代的
    • 其实我想在func中传递(x,y),它们是a和b的值,它将进入一个循环并返回一个新的数据帧。
    • @Raghu:你没有展示你想如何使用x,但这个答案的基本原理是你应该避免 Python 循环和apply,如果可以的话。 Pandas 和 numpy 使用 C 例程,它们的内部循环比 Python 快得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2018-06-21
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2019-04-04
    相关资源
    最近更新 更多