我正在尝试从pandas数据框中的特定列中删除某些字符。由于这一切都在for循环内完成,因此我想在循环内使用if语句对所有“object” dtype列执行操作。
for col in pitchtype :
pitchtype[col] = pitchtype[col].replace(np.nan,0)
if pitchtype[col].dtype == 'object':
pitchtype[col] = pitchtype[col].map(lambda x: x.replace(' %',''))
是否有办法在if语句中使条件成立?
编辑:下面是我的数据框。基本上,标题中带有“%”的列在值中具有“%”符号,这些符号防止它们成为浮点数。我正在尝试删除“%”并在此后将列更改为float类型。
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 264 entries, 0 to 263
数据列(共18列):
Name 264 non-null object
Team 264 non-null object
FB% 264 non-null object
FBv 264 non-null float64
SL% 264 non-null object
SLv 264 non-null float64
CT% 264 non-null object
CTv 264 non-null float64
CB% 264 non-null object
CBv 264 non-null float64
CH% 264 non-null object
CHv 264 non-null float64
SF% 264 non-null object
SFv 264 non-null float64
KN% 264 non-null object
KNv 264 non-null float64
XX% 264 non-null object
playerid 264 non-null int64
dtypes: float64(7), int64(1), object(10)
memory usage: 37.2+ KB
object
周围加引号,否则它就不是一个 dtype,而是一个字符串,上面写着'object'
。 - Rocky Li