您可以先使用
boolean indexing和
replace过滤列
contains值X:
cols = df.columns[df.columns.str.contains('X')]
df[cols] = df[cols].replace({'True': True, 'False': False})
或者如果需要过滤列X:
cols = df.columns[df.columns == 'X']
df[cols] = df[cols].replace({'True': True, 'False': False})
样品:
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)
A B C X
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)
A B C X
0 a1 b1 c1 True
1 a2 b2 c2 False
2 a3 b3 c3 True