For loop to retrieve header for data frame in pandas

I am new to python. I have a data frame that looks like this:

    A   B   C   D   E
0   1   0   1   0   1
1   0   1   0   0   1
2   0   1   1   1   0
3   1   0   0   1   0
4   1   0   0   1   1

How can I write a for loop to collect column names for each row. I expect my result set to look like this:

    A   B   C   D   E   Result
0   1   0   1   0   1   ACE
1   0   1   0   0   1   BE
2   0   1   1   1   0   BCD
3   1   0   0   1   0   AD
4   1   0   0   1   1   ADE

Can anybody help me? Thank!

+4
source share
1 answer

The function dotis executed for this purpose, since you want a matrix dot product between your matrix and the column name vector:

df.dot(df.columns)
Out[5]: 
0    ACE
1     BE
2    BCD
3     AD
4    ADE

If your dataframe is numeric, then first get the logic matrix by checking yours dffor 0:

(df!=0).dot(df.columns)

PS: just assign the result to a new column

df['Result'] = df.dot(df.columns)

df
Out[7]: 
   A  B  C  D  E Result
0  1  0  1  0  1    ACE
1  0  1  0  0  1     BE
2  0  1  1  1  0    BCD
3  1  0  0  1  0     AD
4  1  0  0  1  1    ADE
+9
source

Source: https://habr.com/ru/post/1653492/


All Articles