Reputation: 135
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
Upvotes: 2
Views: 1236
Reputation: 507
You an also do this:
for i in range(len(df)):
df.set_value(i,'Result',[df.columns[(df == 1).iloc[i]]])
Upvotes: 1
Reputation: 2748
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)
Upvotes: 0
Reputation: 38415
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
Upvotes: 1
Reputation: 323226
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
Upvotes: 6