Home > Software design >  How to create a table with data with a formula? (Python)
How to create a table with data with a formula? (Python)

Time:10-03

I'm learning Python by myself and I was doing an experiment, where I want to create two columns of data (column A and column B). However, my experiment needs calculated data. My goal is to create a data frame myself (as you do in excel), but I want to incorporate the formulas I need to get the calculated values for my data.

Would it be easier to use the print() and the escape characters required (\n for line break, \t for tab), to display a table on the screen such as the following?:

Hours (n) Total number
0 200
5 6400
10 204800
15 6553600

For example: the formula I'm using to create this table is Total number=200x2^n

CodePudding user response:

You "could" use \n and \t but that will become awkward very quickly. A better approach is to use
the f-string formatting options to align things as needed.
In this example, your calculation (200 * 2^n) is part of the list comprehension that creates the table values for printing, all in one go. The 15 1 in the range function is needed to include your stated value of 15.

table_values = [(n, 200 * 2**n) for n in range(0, 15 1, 5)]

print(f"{'Hours (n)':<15} Total number")
print("-" * 28)
for h, t in table_values:
    print(f"{h :<15} {t:}")


# Alternatively, right-aligned and with 000-separators...
print(f"{'Hours (n)':<15} Total number")
print("-" * 28)
for h, t in table_values:
    print(f"{h :>2} {t:>24,}")

The output would then look something like this:

Hours (n)       Total number
----------------------------
0               200
5               6400
10              204800
15              6553600

Alternative output including the number alignment and formatting:

Hours (n)       Total number
----------------------------
 0                      200
 5                    6,400
10                  204,800
15                6,553,600

CodePudding user response:

you can use this code

import pandas as pd

# Create a dataframe
df = pd.DataFrame()

# Add Hours column, starting trom zero, ending at 15 with step size of 5
df['Hours(n)'] = range(0,16,5)

# Calcualtion total number using hours
df['Total number'] = 200* 2**(df['Hours(n)'])

#show dataframe
print(df)

# show datafram in a better format
display(df)

The output will look like this

enter image description here

If you further face any issues, please write me back. Cheers :)

  • Related