0

So I need to output a txt file that in one row contains the city-value of all companies in said industry rounded on 2 decimal places. Code works as intended I just need to round them to 2 decimal places. I have some guesses in what seems to be a problem with rounding them but I just can't figure it out. PS I'm new to python and coding in general so I'm sorry if my question seems dumb.

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)
Not_Rakija
  • 11
  • 1
  • 1
    `with open(f'{k} + ".txt", 'w') as textfile:` - mismatching " or ' - also why add a string to an interpolated string: `with open(f'{k}.txt' , 'w') as textfile:` works – Patrick Artner Jan 14 '22 at 11:09
  • Can you please explain what are you meaning by mismatching 'or'? English is not my first language so I'm having trouble understanding the meaning of that part of the sentence. – Not_Rakija Jan 14 '22 at 12:30
  • Look at the color coding of your code. You see that strings are green. Look at your last 5 or so lines. They are mostly green - because in some line you are missing a " or ' to end that lines string. `with open(f'{k} + ".txt", 'w') as textfile:` has an opening `'` that is not closed by your code. – Patrick Artner Jan 14 '22 at 12:38
  • ohhh i see now what you have meant ty so much – Not_Rakija Jan 14 '22 at 12:42

0 Answers0