I have this dataframe:
df0 = pd.DataFrame({'points': [0, 0, -3, 16, 0, 5, -3, 14],
'assists': [0, 0, 2, 0, 1, -7, 0, 6],
'numbers': [0, 0, 1, 6, 10, 5, 8, 7]})
and my desired dataset looks like this:
points assists numbers colX
0 0 0 0
0 0 0 0
-3 2 1 'points-assists-numbers'
16 0 6 'points-numbers'
0 1 10 'assists-numbers'
5 7 5 'points-assists-numbers'
-3 0 8 'points-numbers'
14 8 7 'points-assists-numbers'
A function that create a string from columns names that have values distinct from zero.
Any help?
>Solution :
This kind of operation is well suited to a lambda expression.
Something like this should work:
df0['colX'] = df0.apply(lambda x: '-'.join(c for c in df0.columns if x[c] != 0), axis=1).replace('', 0)
- first it gets a list of the columns that are not 0
- joins the names of those columns with a "-"
- after that, fills blank names with a 0