使用pandas dtype作为条件

2024-06-06 13:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从pandas数据帧的某些列中删除某些字符。我在for循环中执行所有这些操作,因此我希望在循环中使用if语句对所有“object”数据类型列执行操作。在

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类型。在

^{pr2}$

数据列(共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

Tags: 数据pandasforifobjectcol语句字符
2条回答

我想这可能就是你要找的,检查单个对象是否是字符串。在

if pitchtype[col].dtype == object: # No quotes around it!
    pitchtype[col] = pitchtype[col].map(lambda x: x.replace(' %','') if type(x) == str else x)

您可以使用^{}^{}

for col in df.select_dtypes(['object']):
    df[col] = pd.to_numeric(df[col].str.rstrip('%'), errors='coerce')

float的转换由^{}执行。errors='coerce'给出NaN表示不可转换的值。在

相关问题 更多 >