Issue
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:
+---+---------------------+
| 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.])]
Answered By - Mr. Polywhirl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.