简体   繁体   中英

Not sure why lambda fuction is not iterating according to loop

sel_ col10= ['ColumnA']
sel_col_new10= ['ColumnB']
for col, ncol in zip (sel_col10, sel_col_new10) :
    df_test[ncol] = df_test[col]. apply (lambda x: df_test [col] + df_test [ncol] if x== "Not Covered" else df test [ncol])

I was expecting to get it iterated through the whole column so that the formula applies to every cell of the column

Untested, but I think the below is the equivalent of what you are trying to achieve.

selection = df_test[col] == "Not Covered"
df_test.loc[selection, ncol] = df_test.loc[selection, col] + df_test.loc[selection, ncol]

(And I think there are even nicer ways to write this, with equivalent Pandas functionality as numpy.where , but I don't know that one by heart. Search for "Pandas where".)

It seems a bit weird that you use the same column for the selection as the one that you are adding to the new column. But that can work. I assume it means you go from "Not covered" to something like "Not covered - done".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM