首页 > 解决方案 > 使用“%”选择数据并在 pandas 中处理的问题

问题描述

我想在我的 pandas.df 中选择所有带有 '%' 的数字并将其转换为浮点形式(例如从 2% 到 0.02)。目标数字偶尔会传播,所以无法通过行/列来完成。我尝试了以下代码:

df.applymap(lambda x: str(x).contains('%').strip("%").astype(float)/100)

它没有工作...

标签: pandas

解决方案


这应该工作

df=pd.DataFrame({'percent_column':['2%','3%','6%','0.08'],'Other_percent_column':['0.04','0.03','3%','4%']})
df=df.applymap(lambda x: float(x.rstrip('%'))/100 if '%' in x else float(x))
print(df)

结果:

   percent_column  Other_percent_column
0            0.02                  0.04
1            0.03                  0.03
2            0.06                  0.03
3            0.08                  0.04

推荐阅读