pandas - 使用“%”选择数据并在 pandas 中处理的问题
问题描述
我想在我的 pandas.df 中选择所有带有 '%' 的数字并将其转换为浮点形式(例如从 2% 到 0.02)。目标数字偶尔会传播,所以无法通过行/列来完成。我尝试了以下代码:
df.applymap(lambda x: str(x).contains('%').strip("%").astype(float)/100)
它没有工作...
解决方案
这应该工作
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
推荐阅读
- php - 新项目在列末尾添加两次
- reactjs - 如何选择不同的 mui timepicker 变体
- c++ - 非立方区域的莫顿曲线,是 2 的幂
- .net - System.Windows.Forms DataGridView 显示尾随文本而不是前导文本 PowerShell
- r - 如何将 R 脚本和 R markdown 合并到一个文件中?
- javascript - 画布径向渐变以匹配 css 径向渐变
- timestamp - Ecto insert 不会自动填充时间戳字段
- loops - 在groovy中使用循环分配类变量
- javascript - 使用 JavaScript 计算两个变量输入
- c# - CoreWindow.PointerPosition 返回 nullReference