0

I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this enter image description here

The code is this:

    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))

Thanks in advance.

Anonymous
  • 49
  • 1
  • 9

2 Answers2

1

The easiest way to do this, is using pandas.DataFrame. There are two ways to reach the result you want:

Method 1: typing values in Python to create Pandas DataFrame

import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)

Method 2: importing values from an Excel file to create Pandas DataFrame

import pandas as pd

data = pd.read_excel(r'Path where the Excel file is stored\File name.xlsx')
df = pd.DataFrame(data, columns = ['First Column Name','Second Column Name',...])

print (df)

Hope this helped you.

  • The difference is that these values aren't from a file.. they are calculated in the program. But that's nice – Anonymous Jun 01 '20 at 14:42
0

Two solutions:

  1. Don’t use tabs. They advance to the next tab stop which is usually the column number divisible by 8. Notice how your first values are shorter so it throws off where the tab stop ends up.

  2. Set your field widths correctly. %3.2f means your field has a width of 3, but your largest numbers have a width of 6. Use %6.2f instead.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251