Advertisement
fahimkamal63

groceries_table

Jan 29th, 2020
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. """
  2. This script will convert the original groceries list.csv file in a perfect table
  3. Date: 30.01.2020
  4. Fahim Kamal
  5. """
  6. import pandas as pd
  7. # Read the csv file
  8. file = open('groceries list.csv')
  9. raw_data = file.readlines()
  10.  
  11. number_of_columns = 0
  12. rows = []
  13. for row in raw_data:
  14.     # Separate each items from the string
  15.     rows.append(row.split(','))
  16.     # Remove '\n' from the last element of the list
  17.     rows[-1][-1] = rows[-1][-1][0:len(rows[-1][-1])-1]
  18.     # Find the max number of column's from all rows
  19.     number_of_columns = max(number_of_columns, len(rows[-1]))
  20.  
  21. # Create the dictionary for the dataframe
  22. dictionary = {}
  23. for _ in range(number_of_columns):
  24.     dictionary[f'Column {_ + 1}'] = []
  25.     for row in rows:
  26.         if _ < len(row):
  27.             dictionary[f'Column {_ + 1}'].append(row[_])
  28.         else:
  29.             dictionary[f'Column {_ + 1}'].append(None)
  30.  
  31. df = pd.DataFrame.from_dict(dictionary)
  32. df.to_csv('Sample_groceries_table.csv', index=False)
  33.  
  34. # print(dictionary)
  35. # print(rows)
  36. # print(number_of_columns)
  37. print(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement