Skip to content Skip to sidebar Skip to footer

I Want To Replace Values Of Dataframe As A Column Name In Python. How Am I Suppose To Do That?

I want to convert following values using loop. {'Id':2, 'A':'no', 'B':'no', 'C':'no', 'D':'yes'}, {'Id':3, 'A':'yes', 'B':'yes', 'C':'yes', 'D':'no'}, {'Id'

Solution 1:

try this..

this is borrowed from the linked post

Example DataFrame:

>>>dfABCDId2nononoyes3yesyesyesno4yesnoyesno5noyesnoyes

Answer :

>>> df.loc[:, 'A':'D'].replace('yes', pd.Series(df.columns, df.columns)).replace('no', '-')
    ABCDId2---D3ABC-4A-C-5-B-D

Another solution as @– Quang Hoang mentioned..

>>>for col in'ABCD':...  df[col] = df[col].map({'yes':col, 'no':'-'})...>>>df
    A  B  C  D
Id
2   -  -  -  D
3   A  B  C  -
4   A  -  C  -
5   -  B  -  D

OR

>>>for cell in df[['A','B','C','D']].columns:...    df[cell].replace({'yes':col, 'no':'-'}, inplace=True)...>>>df
    A  B  C  D
Id
2   -  -  -  D
3   D  D  D  -
4   D  -  D  -
5   -  D  -  D

Solution 2:

You can use this solution:

import pandas as pd
x = pd.DataFrame([{'Id':2, 'A':"no", 'B':"no", 'C':"no", 'D':"yes"}, 
           {'Id':3, 'A':"yes", 'B':"yes", 'C':"yes", 'D':"no"}, 
           {'Id':4, 'A':"yes", 'B':"no", 'C':"yes", 'D':"no"}, 
           {'Id':5, 'A':"no", 'B':"yes", 'C':"no", 'D':"yes"}])  
x.set_index('Id')
headers = x.columns.to_list()
for col in headers:
    x[col] = x[col].map({"yes":col, "no":"-"}) 

Post a Comment for "I Want To Replace Values Of Dataframe As A Column Name In Python. How Am I Suppose To Do That?"