如果列包含 Pandas 中的字符,请更改列类型

例如,我在某些列(非空对象)中有字符“%”的值


 col1     col2  col3 

'4.24%' '5.22%'  8

但我想要 4.24 和 5.22 作为浮点数。


I have tried with:

for el in df.columns:

    if df[el].str.contains('%').any():

        df[el] = df[el].str.strip("%").astype(float) 

并表示 : AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas


如果我使用:


if df['col1'].str.contains('%').any():

            df['col1'] = df['col1'].str.strip("%").astype(float)

然后工作正常。但是通过所有列的迭代不起作用。


波斯汪
浏览 221回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python