You can first filter the contains columns of the X value with boolean indexing , and then replace :
cols = df.columns[df.columns.str.contains('X')] df[cols] = df[cols].replace({'True': True, 'False': False})
Or, if the filter column needs X :
cols = df.columns[df.columns == 'X'] df[cols] = df[cols].replace({'True': True, 'False': False})
Example:
import pandas as pd df = pd.DataFrame({'A':['a1','a2','a3'], 'B':['b1','b2','b3'], 'C':['c1','c2','c3'], 'X':['True','False','True']}) print (df) ABCX 0 a1 b1 c1 True 1 a2 b2 c2 False 2 a3 b3 c3 True
print (df.dtypes) A object B object C object X object dtype: object cols = df.columns[df.columns.str.contains('X')] print (cols) Index(['X'], dtype='object') df[cols] = df[cols].replace({'True': True, 'False': False}) print (df.dtypes) A object B object C object X bool dtype: object print (df) ABCX 0 a1 b1 c1 True 1 a2 b2 c2 False 2 a3 b3 c3 True
source share