首页 > 解决方案 > 需要将 df.apply 的结果分配给两个新列

问题描述

全部。

我有一个返回两个值的函数。一个是列表,另一个是双精度。

我想使用这样的东西在我的 df 中创建两个新列,并使用 .apply 逐行填充这些列。

def f(a_list):
     #do some stuff to the list
     if(stuff):
          make_new_stuff_happen         

     #return results of stuff
     return new_list, a_double



def main():
     df['new_col1'], df['new_col2'] = df.apply(lambda x: f(x['some_col']))

感谢您的任何帮助,您可以提供。

标签: pythonpandasfunctionlambda

解决方案


几点注意事项:

  • 我认为double你的意思是float在 Python 中?
  • 即使是示例,我也会将您的函数和变量命名为更有意义的名称,以便更容易诊断

也许这个答案会有所帮助:

如果这是您正在使用的原始数据框:

col_1  |  col_2  |  col_3
-------------------------
  1    |    3    |   3
  2    |    3    |   4
  3    |    1    |   1

你可以有这样的功能:

def transform_into_two_columns(original_val_from_row):
    
    # do some stuff to the list:
    
    # example 1: multiply each row by 2 & save output to new list (this would be "new_list" in your question)
    original_val_times_2 = original_val_from_row*2
    
    # example 2: sum all values in list/column (this would be "a_double" in your question)
    original_val_plus_2 = original_val_from_row+2.1

    return original_val_times_2, original_val_plus_2

然后,您可以将该函数的输出保存到列表中:

list_of_tuples = df['col_2'].apply(lambda x: transform_into_two_columns(x)).to_list()

然后,list_of_tuples您可以创建 2 个新列:

df[['NEW_col_4', 'NEW_col_5']] = pd.DataFrame(list_of_tuples, index=df.index)

您的新数据框将如下所示:

col_1  |  col_2  |  col_3  | NEW_col_4  | NEW_col_5
---------------------------------------------------
  1    |    3    |   3     |     6      |    5.1   
  2    |    3    |   4     |     6      |    5.1
  3    |    1    |   1     |     2      |    3.1

推荐阅读