如何将填充有数字的数据框列转换为 python 中的字符串?

How do I convert a dataframe column filled with numbers to strings in python?

我有一个数据框 dfA,其中有一列 diff,其中每个值都是一个数字,例如:

dfA['diff']

输出:

88    -120.0
89    -130.0
90    -105.0
91    -115.0
92    -120.0
93    -110.0
94    -120.0
95    -115.0
96    -120.0
97    -105.0
98    -130.0
99    -115.0
100   -115.0
101    120.0
102   -155.0
103    115.0
104   -150.0
105   -190.0
106    140.0
107    170.0
108   -240.0
109    115.0
110   -160.0
111   -125.0
112   -110.0
115   -205.0
116    150.0
117   -155.0
118    115.0
Name: diff, dtype: float64

我想:

示例:

88    -120
89    -130
90    -105
91    -115
92    -120
93    -110
94    -120
95    -115
96    -120
97    -105
98    -130
99    -115
100   -115
101   +120
102   -155
103   +115
104   -150
105   -190
106   +140
107   +170
108   -240
109   +115
110   -160
111   -125
112   -110
115   -205
116   +150
117   -155
118   +115

请帮忙,谢谢!

将值转换为整数,将字符串转换为帮助程序系列 s,因此可以比较原始列以获得更大的 0Series.mask 以获得前缀 +:

s = dfA['diff'].astype(int).astype(str)
dfA['diff'] = s.mask(dfA['diff'].gt(0), '+' + s)

print (dfA)
     diff
98   -130
99   -115
100  -115
101  +120
102  -155
103  +115
104  -150

带格式:

dfA['diff'] = dfA['diff'].map(lambda x: '{0:+}'.format(int(x)))