首页 > 解决方案 > 仅在缺少数字的单元格中替换熊猫数据框中的“-”字符

问题描述

我正在尝试将“-”字符串字符转换为 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

标签: pandas

解决方案


使用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)

推荐阅读