I have a df like this:
0 1 2 3 4 5
abc 0 1 0 0 1
bcd 0 0 1 0 0
def 0 0 0 1 0
How can I convert the dataframe cells to be the column name if there's a 1 in the cell? Looks like this:
0 1 2 3 4 5
abc 0 2 0 0 5
bcd 0 0 3 0 0
def 0 0 0 4 0
Let us try
df.loc[:,'1':] = df.loc[:,'1':] * df.columns[1:].astype(int)
df
Out[468]:
0 1 2 3 4 5
0 abc 0 2 0 0 5
1 bcd 0 0 3 0 0
2 def 0 0 0 4 0
I'd suggest you simply do the logic for each column, where the value is 1
in the given column, set the value as the column name
for col in df.columns:
df.loc[df[col] == 1, col] = col
We can use np.where
over the whole dataframe:
values = np.where(df.eq(1), df.columns, df)
df = pd.DataFrame(values, columns=df.columns)
0 1 2 3 4 5
0 abc 0 2 0 0 5
1 bcd 0 0 3 0 0
2 def 0 0 0 4 0
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.