0

I want to replace the values of specific columns. I can change the values one by one but, I have hundreds of columns and I need to change the columns starting with a specific string. Here is an example, I want to replace the string when the column name starts with "Q14"

df.filter(regex = 'Q14').replace(1, 'Selected').replace(0, 'Not selected')

The above code is working. But, how I can implement it in my dataframe? As this is the function so I can't use inplace.

3 Answers 3

2

Consider below df:

In [439]: df = pd.DataFrame({'Q14_A':[ 1,0,0,2], 'Q14_B':[0,1,1,2], 'Q12_A':[1,0,0,0]})

In [440]: df
Out[440]: 
   Q14_A  Q14_B  Q12_A
0      1      0      1
1      0      1      0
2      0      1      0
3      2      2      0

Filter columns that start with Q14, save it in a variable:

In [443]: cols = df.filter(regex='^Q14').columns

Now, change the above selected columns with your replace commands:

In [446]: df[cols] = df[cols].replace(1, 'Selected').replace(0, 'Not selected')

Output:

In [447]: df
Out[447]: 
          Q14_A         Q14_B  Q12_A
0      Selected  Not selected      1
1  Not selected      Selected      0
2  Not selected      Selected      0
3             2             2      0
Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate over all columns and based on matched condition apply column transformation using apply command:

for column in df.columns:
    if column.startswith("Q"):
        df[column] = df[column].apply(lambda x: "Selected" if x == 1 else "Not selected")

Comments

1

Using pandas.Series.replace dict

df = pd.DataFrame({'Q14_A':[ 1,0,0,2], 'Q14_B':[0,1,1,2], 'Q12_A':[1,0,0,0]})
cols = df.filter(regex='^Q14').columns

replace_map = {
    1: "Selected",
    0 : "Not Selected"

}

df[cols] = df[cols].replace(replace_map)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.