繁体   English   中英

有没有办法将 textfile.write 舍入到小数点后 2 位?

[英]Is there any way to round textfile.write to 2 decimal places?

所以我需要 output 一个 txt 文件,其中一行包含该行业所有公司的城市价值,四舍五入到小数点后 2 位。 代码按预期工作我只需要将它们四舍五入到小数点后 2 位。 我对四舍五入似乎有什么问题有一些猜测,但我就是想不通

import os

try:
   import pandas as pd
except ImportError:
     os.system("pip install pandas")


def main(filename='statups.csv'):
    # reading the csv
    df = pd.read_csv(filename)

    # grouping by industry name and city and summing the value
    ast = df.groupby(['Industry', 'City'], as_index=False)['Valuation 
    ($B)'].sum()
    # sorting the columns
    ast = ast.sort_values(by=['Industry', 'Valuation ($B)'], ascending= 
    [True, False])

# could have done with pandas but ran into saving group by to csv function error
# and went with inefficient way

   # creating the dictionary to hold each industry value
   my_dict = {}
   for val in ast['Industry'].unique():
       val = val.replace(" ", '_')
       my_dict[val] = []

   # storing the value in dictionary
   for index, row in ast.iterrows():
       val = row['Industry'].replace(" ", '_')
       my_dict[val].append(str(row['City']) + "-" + str(row['Valuation 
       ($B)']))

   # saving the value from the dictionary
   for k in my_dict.keys():
       with open(f'{k} + ".txt", 'w') as textfile:
           for element in my_dict[k]:
              textfile.write('{:0.3f}'.format(element) + "\n")         
if __name__ == '__main__':
    filename = input('Enter filename: ')
    main(filename)


 

Python 中的 f 字符串格式将为您进行舍入。 因此你可以这样做:

for k, v in my_dict.items():
  with open(f'{k}.txt', 'w') as textfile:
    for v_ in v:
      textfile.write(f'{float(v_):.2f}\n')

这将失败 v_ 无法转换为浮点数

有几种格式化值的方法。 一种可能性是使用str.format()方法(有关详细信息,请参阅https://docs.python.org/3/library/stdtypes.html#str.format )。

根据您的代码并假设字典值是数字列表:

my_dict = { "a": [3.17213], "b": [3.98992] } # or similar

for k in my_dict.keys():
    with open(k + ".txt", 'w') as textfile:
        for element in my_dict[k]:
           textfile.write('{:0.3f}'.format(element) + "\n") # write with a precision of 3 digits after the decimal point

所以我找到了一个解决方案,我只需要改变

my_dict[val].append(str(row['City']) + "-" + str(row['Valuation ($B)']))

my_dict[val].append(str(row['City']) + "-" + str('{:.2f}'.format(row['Valuation ($B)'])))`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM