【问题标题】:python dataframe When converting Int to Str, .0 is added at the endpython dataframe 将Int转换为Str时,最后加上.0
【发布时间】:2018-12-21 15:17:10
【问题描述】:

打印(数据框)

      Total Price      test_num                                        
0           71.7       2.04256e+14 
1           39.5       2.04254e+14 
2           82.2       2.04188e+14
3           42.9       2.04171e+14

上传到 Mongo db 并将其转换为 Str 时出现错误。

打印(data_frame.astype(str))

 Total Price     test_num                        
0           71.7  204255705072224.0           
1           39.5  204253951078915.0         
2           82.2  204188075120577.0          
3           42.9  204171098699772.0       

将 Int 转换为 Str 时,在末尾添加 .0。 如何有效消除 .0? 谢谢

【问题讨论】:

  • df = df.apply(lambda x: x.replace('0.0', ""))

标签: python string python-3.x pandas dataframe


【解决方案1】:

int64使用astype

df['test_num'] = df['test_num'].astype('int64')
#alternative
#df['test_num'] = df['test_num'].astype(np.int64)
print (df)
   Total  Price         test_num
0      0   71.7  204256000000000
1      1   39.5  204254000000000
2      2   82.2  204188000000000
3      3   42.9  204171000000000

解释

您可以检查转换列的dtype - 它返回float64

print (df['test_num'].dtype)
float64

转换为字符串后,它会删除指数符号并转换为floats,因此添加了跟踪0

print (df['test_num'].astype('str'))
0    204256000000000.0
1    204254000000000.0
2    204188000000000.0
3    204171000000000.0
Name: test_num, dtype: object

【讨论】:

  • 如果您能提供解释,我将删除我的答案。这并不能解释出了什么问题。
  • @jpp - 我试试,但需要更多时间。
  • @jpp - 我尝试了一下,但应该会更好,so post question
  • 我刚看到你的回答。对不起。
猜你喜欢
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2021-12-28
  • 2023-03-29
相关资源
最近更新 更多