Given a DataFrame df
:
d e f
a 0 [2] [3]
b [1] 0 [3]
c [0] [2, 3] [3, 1]
I simply want to append values on axis=1 for the result of:
d e f appended
a 0 [2] [3] [0,2,3]
b [1] 0 [3] [1,0,3]
c [0] [2, 3] [3, 1] [0,2,3,3,1]
Surprisingly df['appended'] = df.sum(axis=1)
would do it, if not for the 0
values (which aren't list) and it returns zeros for each row.
I know this is a dumb question, but I've taken up pandas just recently, and I am yet to get a feel for it.
Can you suggest anything please?
@EDIT
Yes, I tried to replace zeros with a list (although I'd rather not do that because I need those zeros to stay zeros in my original df, and creating a new df may not be the best option?):
def mk_list(x):
if not isinstance(x, list):
x = [x]
return x
df2 = df.apply(mk_list)
anyways this produced all NaN
, I must be doing it wrongly.
d [[nan, nan, nan]]
e [[nan, nan, nan]]
f [[nan, nan, nan]]