如何在将百分比转换为整数之前删除百分比

2024-09-23 06:35:40 发布

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

我有一个由2列组成的数据帧。我想将COUNT列转换为int。它使我不断给出值错误:无法分析位置0处的字符串“0.58%”

METRIC      COUNT
Scans         125487
No Reads      2541
Diverts       54710
No Code%      0.58%
No Read%      1.25%


df['COUNT'] = df['COUNT'].apply(pd.to_numeric)

转换前如何删除%1


Tags: to数据no字符串dfcount错误metric
2条回答

str.strip的IIUC

pd.to_numeric(df.col1.str.strip('%'))
0    1
1    2
2    3
Name: col1, dtype: int64

试试看,我假设0.58%作为字符串读入,这意味着replace函数将不使用任何内容替换“%”,在这一点上,它可以转换为一个数字

import pandas as pd
df = pd.DataFrame({'col1':['1','2','3%']})
df.col1.str.replace('%','').astype(float)

相关问题 更多 >