在pandas datafram中将数字转换为2位浮点数

2024-06-26 04:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,如下所示:

Names   Cider   Juice   Subtotal (Cider)   Subtotal (Juice) Total
Richard   13        9           $ 71.5            $ 40.5  $ 112.0
George     7       21           $ 38.5            $ 94.5  $ 133.0
Paul       0       23           $ 0.0            $ 103.5  $ 103.5
John      22        5           $ 121.0           $ 22.5  $ 143.5
Total     42       58           $ 231.0          $ 261.0  $ 492.0
Average 10.5     14.5           $ 57.75          $ 65.25  $ 123.0

我希望所有浮点数都是.2f(2位浮点数)。.applymap()不工作,因为我在“Names”列中有字符串类型。有没有办法使用.applymap()或者有没有更好的方法?

import pandas as pd

df = pd.DataFrame(columns=["Names", "Cider", "Juice", "Subtotal(Cider)", "Subtotal(Juice)", "Total"])
people_ordered = input('How many people ordered? ')  # type str

# Create the 4x3 table from user input
for i in range(int(people_ordered)):
    names = input("Enter the name of Person #{}: ".format(i+1))  # type str

    cider_orderred = float(input("How many orders of cider did {} have? ".format(names)))  # type str -> int
    #cider_orderred = float("{:.2f}".format(cider_orderred))
    juice_orderred = float(input("How many orders of juice did {} have? ".format(names)))  # type str -> int
    #juice_orderred = float("{:.2f}".format(juice_orderred))

    # store the values of the subtotals from user inputs
    cider_sub = 5.50 * cider_orderred  # type float
    cider_sub = float("{:.2f}".format(cider_sub))
    juice_sub = 4.50 * juice_orderred  # type float
    juice_sub = float("{:.2f}".format(juice_sub))
    total = cider_sub + juice_sub  # type float
    total = float("{:.2f}".format(total))

    # create the 4x6 table
    df1 = pd.DataFrame(
        data=[[names, int(cider_orderred), int(juice_orderred), round(cider_sub, 2), round(juice_sub, 2), round(total, 2)]],
        columns=["Names", "Cider", "Juice", "Subtotal(Cider)", "Subtotal(Juice)", "Total"])

    # merge the the 4x3 into the 4x6 table
    df = pd.concat([df, df1], axis=0)

# add rows of "Total" and "Average"
df.loc['Total'] = df.sum()
df.loc['Average'] = df[:int(people_ordered)].mean()

# Adding "$" to the prices
df['Subtotal(Cider)'] = '$ ' + df['Subtotal(Cider)'].astype(str)
df['Subtotal(Juice)'] = '$ ' + df['Subtotal(Juice)'].astype(str)
df['Total'] = '$ ' + df['Total'].astype(str)

# Set the row name to "Total" and "Average"
df.iloc[int(people_ordered),0] = 'Total'
df.iloc[int(people_ordered)+1,0] = 'Average'

# Set the index according to 'Names'
df.index = range(len(df.index))
df.set_index('Names', inplace=True)


print(df)

更新了我的当前解决方案,如上所述。


Tags: theformatdfnamestypefloatintjuice