简体   繁体   中英

print columns names if row equal to value in python

How can i iterate between rows and print the columns names in one column if the value = 1

mydata = [{'a' : '0', 'b': 1, 'c': 0}, {'a' : 1, 'b': 0, 'c':1}, {'a' : '0', 'b': 1, 'c':1}] 
df = pd.DataFrame(mydata)

a   b   c   Result 
0   1   0   b 
1   0   1   a , c
0   1   1   b , c

The result only shows the columns name that are equal to 1

Using dot

df['New']=df.astype(int).dot(df.columns+',').str[:-1]
df
Out[44]: 
   a  b  c  New
0  0  1  0    b
1  1  0  1  a,c
2  0  1  1  b,c

Use boolean indexing to index the row, and join column names

df['new'] = df.eq(1).apply(lambda x: ', '.join(x[x].index), axis = 1)

    a   b   c   new
0   0   1   0   b
1   1   0   1   a, c
2   0   1   1   b, c

You an also do this:

for i in range(len(df)):
    df.set_value(i,'Result',[df.columns[(df == 1).iloc[i]]])

More beginners solutions would be

for index, row in df.iterrows():
    for key in row.keys():
        print(key if row.get(key) == 1 else None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM