在熊猫中从浮点数转换为字符串时如何拥有相同的小数位数?



在熊猫中将浮点列转换为字符串时遇到问题。我想在字符串中具有相同数量的小数位数(例如 2(,以便以后添加货币符号。

import pandas as pd
Data = {'Product': ['ABC','XYZ'],
'Price': ['250.00','270.43']}
df = pd.DataFrame(Data)
df['Price'] = df['Price'].astype(float)
df['Product'] = df['Product'].astype(str)
print(df)
print(df.dtypes)
df['Price'] = df['Price'].astype(str)
print(df)
print(df.dtypes)

我得到什么:

Product   Price
0     ABC  250.00
1     XYZ  270.43
Product     object
Price      float64
dtype: object
Product   Price
0     ABC   250.0
1     XYZ  270.43
Product    object
Price      object
dtype: object

我尝试将 250.00 作为字符串。 谢谢。

您可以使用format进行应用:

df['Price'] = df['Price'].apply("{:.02f}".format)

输出:

Product   Price
0     ABC  250.00
1     XYZ  270.43

这是这个问题的重复

df['Price'] = df['Price'].astype(str)
df["Price"] = df['Price'].str.extract('(d+(?:.d+)?)', 
expand=False).astype(float).round(2)
print(df)
print(df.dtypes)

最新更新