首页 > 解决方案 > Trailing chars in Pandas Series - How to make the sign suffix a prefix?

问题描述

I have a Series set that contains negative values using a trailing minus, like that: 1.22-. I want to change those in an elegant and performant way to: -1.22.

How can I do that.

I have tried this:

In [1]: pd.Series(['1.22-', '-9.99', np.nan]).str.replace('-$', '-^')

Which results in that:

Out[1]:
0       1.22-^
1       -9.99
2       NaN
dtype: object

标签: pythonpandas

解决方案


我会这样做:

negatives = series.str[-1] == '-'
series[negatives] = '-' + series[negatives].str[:-1]

推荐阅读