pandas 在熊猫数据框中将浮点数转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48558107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting float to string in pandas dataframe
提问by jezrael
I have a dataframe in pandas containing datetime and float data.
我在 Pandas 中有一个包含日期时间和浮点数据的数据框。
time price1 price2
2018-02-01T00:00:00.000Z 1.4526547885 1.654775563
I need to convert the columns to string format such that the price1 and price2 columns shows number upto 4 decimal places and the time is displayed as: 01,02,2018 00:00:00
我需要将列转换为字符串格式,以便 price1 和 price2 列显示最多 4 个小数位的数字,时间显示为:01,02,2018 00:00:00
Any leads on this is appreciated. Thanks
对此的任何线索表示赞赏。谢谢
回答by jezrael
You can use dt.strftime
for formating datetime
s and then custom format of float
s:
您可以dt.strftime
用于格式化datetime
s 然后自定义float
s格式:
df['time'] = df['time'].dt.strftime('%Y,%m,%d %H:%M:%S')
cols = ['price1','price2']
df[cols] = df[cols].applymap(lambda x: '{0:.4f}'.format(x))
print (df)
time price1 price2
0 2018,02,01 00:00:00 1.4527 1.6548
回答by Rakesh
回答by Joe
This should work:
这应该有效:
df["price1"] = df["price1"].round(4).astype(str)
df["price2"] = df["price2"].round(4).astype(str)
df['time'] = df['time'].dt.strftime('%d,%m,%Y %H:%M:%S')