Home > OS >  Extract values with map function
Extract values with map function

Time:04-15

You can see my dataset below. I want to transform this table and have the names of the columns in one column [Names] depending on that do these columns have some value or not.

import pandas as pd
import numpy as np

data = { 
        'store_A': [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_B': [0,100,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_C': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_D': [0,100,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_E': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_F': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_G': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_H': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_I': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_J': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_K': [0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100], 
        'store_L': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_M': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_N': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_O': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_P': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_Q': [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100], 
        'store_R': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_S': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_T': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_U': [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
        'store_other': [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100], 
       }


df = pd.DataFrame(data, columns = ['store_A','store_B','store_C','store_D','store_E','store_F','store_G','store_H','store_I','store_J','store_K',
                'store_L','store_M','store_N','store_O','store_P','store_Q','store_R','store_S','store_T','store_U','store_other'])


df

In the end, I need to have one column which contains the above-explained columns, please see the picture below:

enter image description here

So can anybody help me how to solve this problem?

CodePudding user response:

You can apply a filter for each row and join the column names of each row's columns with a non-zero value:

df['Names'] = df.apply(lambda column: ','.join(df.columns[column != 0]), axis=1)

  • Related