熊猫-带条件的lambda和功能输入

时间:2020-03-10 14:36:41

标签: python pandas lambda apply

需要使用lambda并申请以下伪代码。随着实现更多语法问题,我为实现它,遍历DF和创建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;

2 个答案:

答案 0 :(得分:1)

     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

输出

change_balance(int(message.chat.id)

答案 1 :(得分: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