pandas - 仅在缺少数字的单元格中替换熊猫数据框中的“-”字符
问题描述
我正在尝试将“-”字符串字符转换为 np.nan,同时保留表示负浮点数/整数的字符串,以便在删除表示不存在数据的“-”字符后将其转换为浮点数。
我已经尝试为此使用 .applymap() ,因为我想将其应用于整个数据帧,但它不起作用。
这是代码行:
dataframe.applymap(lambda x: None if (x[-1] == '-'))
这是数据框的示例:
Metric 2020 2019 2018 2017
Revenue Growth % 344.17 -14.88 107.11 -
Shares Change % 0.23 0 - -
Gross Margin % 87.7 84 89.3 84.9
Operating Margin % -17.1 -167.2 -42.2 -99.5
解决方案
使用replace
和正则表达式参数:
>>> df.replace(r'^-$', np.NaN, regex=True)
Metric 2020 2019 2018 2017
Revenue Growth % 344.17 -14.88 107.11 NaN
Shares Change % 0.23 0.00 NaN NaN
Gross Margin % 87.70 84.00 89.3 84.9
Operating Margin % -17.10 -167.20 -42.2 -99.5
如果要转换为浮点数:
>>> df.filter(regex='\d+').replace(r'^-$', np.NaN, regex=True).astype(float)
推荐阅读
- kotlin - JUnit 测试中的 Kotlin 内联类
- scala - Scala Play + Slick:如何将依赖项注入 Spec 测试?
- google-analytics-api - GoogleAnalytics API 受众 > 技术 > 网络 > 服务提供商
- ios - 绘制 MTLBuffer 的一部分?
- android - Zxing QR码扫描仪代码在片段中不起作用
- c# - 在基类中创建枚举的别名
- java - 使用 IntelliJ 在类路径中找不到 application.yaml
- python - 将熊猫系列列表转换为熊猫数据框
- flutter - Flutter:浮动动作按钮固定位置
- c# - 如何在同一个项目中获取整数/双打到另一个页面?