Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the name of columns from rows distinct from zero python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading