Home > Enterprise >  replace entire column if row value is between x in python
replace entire column if row value is between x in python

Time:09-23

I want to replace all column values, if the first row value is between 5 and 10

here is my df

df = pd.DataFrame(data={'a':[13,5,6,21,9],
                        'b': [11,5,6,1,2], 
                        'c': [9,28,45,61,31],
                        'd': [5,16,23,1,23]})

and here is my command that is not working..

c = df.columns
df.loc[df.loc[0].between(5,10), c] = 'test'

expected output would be like this

df = pd.DataFrame(data={'a':[13,5,6,21,9],
                        'b': [11,5,6,1,2], 
                        'c': ['test','test','test','test','test'],
                        'd': ['test','test','test','test','test']})

any suggestions are welcome, thank you

CodePudding user response:

Since the condition is for columns, make sure it goes to the column positions:

df.loc[:, df.loc[0].between(5, 10)] = 'test'

df    
    a   b     c     d
0  13  11  test  test
1   5   5  test  test
2   6   6  test  test
3  21   1  test  test
4   9   2  test  test
  • Related