Issue
I have an empty column that is dependent on other 4 columns in the same df. Each row only contain the same string or NaN so I want to grab the first string that pops up in the columns.
I want to iterate through the 4 columns and if one of them contain a value that is not NaN, I want to print it in empty, if they're all NaN then I want empty to be NaN.
empty | 1 | 2 | 3 | 4 |
---|---|---|---|---|
NaN | NaN | apple | NaN | |
duck | NaN | duck | NaN | |
NaN | NaN | NaN | NaN |
This is my desired outcome.
empty | 1 | 2 | 3 | 4 |
---|---|---|---|---|
apple | NaN | NaN | apple | NaN |
duck | duck | NaN | duck | NaN |
NaN | NaN | NaN | NaN | NaN |
Solution
Try .bfill(axis=1)
:
df["Empty"] = df.loc[:, "1":].bfill(axis=1)["1"]
print(df)
Prints:
Empty 1 2 3 4
0 apple NaN NaN apple NaN
1 duck duck NaN duck NaN
2 NaN NaN NaN NaN NaN
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.