[英]How to have the same number of decimal places when converting from float to string in pandas?
在 pandas 中將浮點列轉換為字符串時出現問題。 我想在字符串中使用相同的小數位數(eg2),以便稍后添加貨幣符號。
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)
Output:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.