Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

prettytable is updating all rows in the table

I am facing a difficulty with a package for building beautiful tables. I would like gradJ to be updated in parts, just like the term i.

I would like to see this:

  +---+---------------------+
  | i |        GradJ        |
  +---+---------------------+
  | 0 | [1. 0. 0. 0. 0. 0.] |
  | 1 | [1. 2. 0. 0. 0. 0.] |
  | 2 | [1. 2. 3. 0. 0. 0.] |
  | 3 | [1. 2. 3. 4. 0. 0.] |
  | 4 | [1. 2. 3. 4. 5. 0.] |
  | 5 | [1. 2. 3. 4. 5. 6.] |
  +---+---------------------+

However, my code returns this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  +---+---------------------+
  | i |        GradJ        |
  +---+---------------------+
  | 0 | [1. 2. 3. 4. 5. 6.] |
  | 1 | [1. 2. 3. 4. 5. 6.] |
  | 2 | [1. 2. 3. 4. 5. 6.] |
  | 3 | [1. 2. 3. 4. 5. 6.] |
  | 4 | [1. 2. 3. 4. 5. 6.] |
  | 5 | [1. 2. 3. 4. 5. 6.] |
  +---+---------------------+

I simplified the code that is causing the problem.

from prettytable import PrettyTable
import numpy

myTable = PrettyTable(["i", "GradJ"])
gradJ = numpy.zeros(6)
for i in range(6):
    gradJ[i] = i+1
    myTable.add_row([i, gradJ[:]])
print(myTable)

I have read the PrettyTable documentation, but I still can’t figure out what I’m doing wrong.

>Solution :

Since a NumPy array is not a standard list, calling [:] will not properly create a copy.

Here is the correct usage using numpy.ndarray.copy:

from prettytable import PrettyTable
import numpy

myTable = PrettyTable(["i", "GradJ"])
gradJ = numpy.zeros(6)
for i in range(6):
    gradJ[i] = i+1
    myTable.add_row([i, gradJ.copy()]) # Use numpy.ndarray.copy
print(myTable)

Here is a modified version that removes the dependency on PrettyTable and demonstrates NumPy’s copy() method.

import numpy

size, rows = 6, []

# Populate the table
row = numpy.zeros(size)
for i in range(size):
    row[i] = i + 1 # Fill in the corresponding column
    rows.append([i, row.copy()]) # Call .copy(), not [:]

# Display the table
for row in rows:
    print(row)

Output:

[0, array([1., 0., 0., 0., 0., 0.])]
[1, array([1., 2., 0., 0., 0., 0.])]
[2, array([1., 2., 3., 0., 0., 0.])]
[3, array([1., 2., 3., 4., 0., 0.])]
[4, array([1., 2., 3., 4., 5., 0.])]
[5, array([1., 2., 3., 4., 5., 6.])]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading