My matrix looks like this.
['Hotel', ' "excellent"', ' "very good"', ' "average"', ' "poor"', ' "terrible"', ' "cheapest"', ' "rank"', ' "total reviews"']
['westin', ' 390', ' 291', ' 70', ' 43', ' 19', ' 215', ' 27', ' 813']
['ramada', ' 136', ' 67', ' 53', ' 30', ' 24', ' 149', ' 49', ' 310 ']
['sutton place', '489', ' 293', ' 106', ' 39', ' 20', ' 299', ' 24', ' 947']
['loden', ' 681', ' 134', ' 17', ' 5', ' 0', ' 199', ' 4', ' 837']
['hampton inn downtown', ' 241', ' 166', ' 26', ' 5', ' 1', ' 159', ' 21', ' 439']
['shangri la', ' 332', ' 45', ' 20', ' 8', ' 2', ' 325', ' 8', ' 407']
['residence inn marriott', ' 22', ' 15', ' 5', ' 0', ' 0', ' 179', ' 35', ' 42']
['pan pacific', ' 475', ' 262', ' 86', ' 29', ' 16', ' 249', ' 15', ' 868']
['sheraton wall center', ' 277', ' 346', ' 150', ' 80', ' 26', ' 249', ' 45', ' 879']
['westin bayshore', ' 390', ' 291', ' 70', ' 43', ' 19', ' 199', ' 813']
I want to remove the top row and the 0th column from this and create a new matrix.
How do I do this?
Normally in java or so Id use the following code:
for (int y; y< matrix[x].length; y++)
for(int x; x < matrix[Y].length; x++)
{
if(x == 0 || y == 0)
{
continue
}
else
{
new_matrix[x][y] = matrix[x][y];
}
}
Is there a way such as this in python to iterate and selectively copy elements?
Thanks
EDIT
Im also trying to convert each matrix element from a string to a float as I iterate over the matrix.
This my updated modified code based on the answer below.
A = []
f = open("csv_test.csv",'rt')
try:
reader = csv.reader(f)
for row in reader:
A.append(row)
finally:
f.close()
new_list = [row[1:] for row in A[1:]]
l = np.array(new_list)
l.astype(np.float32)
print l
However Im getting an error
--> l.astype(np.float32)
print l
ValueError: setting an array element with a sequence.
The Basic Idea
Here’s what I came up with:
You can pass your 2d list to the numpy array constructor, slice the 2d array to get rid of the first row and column and then use the
astypemethod to convert everything to a float.All on one line, that’d be:
The ValueError
You’re getting a
ValueErrorbecause you actually have a jagged array. Using the variablenew_listfrom the code in your question you can prove this to yourself:The last row is only of length 8, instead of 9, like all the others. Given a 2d jagged list, the
numpy.arrayconstructor will create a 1d numpy array with adtypeofobject. The entries in that array are Python lists. Theastypecall is attempting to convert Python lists tofloat32, which is failing. I’m guessing this was just a case of human error. If you fix the missing entry, you should be good to go.