python - 需要将 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']))
感谢您的任何帮助,您可以提供。
解决方案
几点注意事项:
- 我认为
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
推荐阅读
- pandas - 如何在熊猫条形图中使 xticks 居中?
- javascript - 续集错误 - “TypeError:hooks.concat 不是函数”
- ios - 在 iOS 中以波形剪切视图
- stubs - Mountebank:能够为存根添加名称
- regex - 正则表达式从括号中提取第二个匹配记录
- java - 这个 while(true) 循环如何退出?
- javascript - 在 Bootstrap 4 模式中打开特定幻灯片
- c++ - CMake 在 Windows 10 下使用 GTest - 致命错误 LNK1104:无法打开文件“gtest.lib”,但存在调试“gtestd.lib”
- c# - 如何在进行正则表达式搜索时排除组合?
- vba - Excel将listobject A(tableA)的几列中的数据一个接一个地复制到listobject B(tableB)的一列中