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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:07:18  来源:igfitidea点击:

Converting float to string in pandas dataframe

pythonpython-3.xpandas

提问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.strftimefor formating datetimes and then custom format of floats:

您可以dt.strftime用于格式化datetimes 然后自定义floats格式:

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

You can use the roundmethod to show only 4 decimals. and use .apply(str) to convert it to string object

您可以使用舍入方法仅显示 4 位小数。并使用 . apply(str) 将其转换为字符串对象

EX:

例如

df["price1"] = df["price1"].round(4).apply(str)
df["price2"] = df["price2"].round(4).apply(str)

回答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')