Advertisement
fahimkamal63

groceries

Jan 29th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. """
  2. Python file for operations in groceries items
  3. Date: 29.01.2020
  4. """
  5. import pandas as pd
  6.  
  7. # Read the data file
  8. # raw_data = open('groceries list.csv')
  9. data_rows = raw_data.readlines()
  10.  
  11. # Separate each item and save them in a list
  12. data_matrix = [data.split(',') for data in data_rows]
  13.  
  14. # Find all unique items and calculate how many time they appear in the file
  15. groceries_items = {}
  16. for data in data_matrix:
  17.     # remove the '\n' from the last item in the list
  18.     data[-1] = data[-1][0:len(data[-1]) - 1]
  19.     for item in data:
  20.         if item in groceries_items:
  21.             # If item present in the dictionary then increment it's value by one
  22.             groceries_items[item] += 1
  23.         else:
  24.             # Else create a new key in the dictionary
  25.             groceries_items[item] = 1
  26.  
  27.  
  28. # Print the dictionary
  29. # print(groceries_items)
  30. for key, value in groceries_items.items():
  31.     print(f'key: {key},\nvalues:{value}')
  32. print(f'Total items: {len(groceries_items)}')
  33.  
  34. # Create the matrix for dataframe
  35. # matrix = [list(groceries_items.keys()), list(groceries_items.values())]
  36. matrix = {'Items': list(groceries_items.keys()), 'Count': list(groceries_items.values())}
  37.  
  38. print(matrix)
  39.  
  40. # Create the dataframe
  41. df = pd.DataFrame.from_dict(matrix)
  42. # Sort the dataframe
  43. df = df.sort_values(['Count'], ascending=False)
  44.  
  45. # Create the csv file
  46. # df.to_csv('sample_groceries_output.csv', index=False)
  47. df.to_csv('final_groceries_output.csv', index=False)
  48.  
  49. print(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement