sum columns of part of 2D array Python - python

INPUT:
M = [[1,2,3],
[1,2,3],
[1,2,3]]
how take the sum of the columns in the two first rows and implement it in the array M
OUTPUT:
M = [[2,4,6],
[1,2,3]]

Use numpy.add.reduceat:
import numpy as np
M = [[1,2,3],
[1,2,3],
[1,2,3]]
np.add.reduceat(M, [0, 2])
# indices [0,2] splits the list into [0,1] and [2] to add them separately,
# you can see help(np.add.reduceat) for more
# array([[2, 4, 6],
# [1, 2, 3]])

M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
M[:2] = [[a + b for a, b in zip(M[0], M[1])]]
print(M) # [[5, 7, 9], [7, 8, 9]]
Things to google to understand this:
M[:2] =: python slice assignment
[... for .. in ...]: python list comprehension
for a, b in ...: python tuple unpacking loop

Related

Selecting a range of columns in Python without using numpy

I want to extract range of columns. I know how to do that in numpy but I don't want to use numpy slicing operator.
import numpy as np
a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
arr = np.array(a)
k = 0
print(arr[k:, k+1]) # --> [2 7]
print([[a[r][n+1] for n in range(0,k+1)] for r in range(k,len(a))][0]) # --> [2]
What's wrong with second statement?
You're overcomplicating it. Get the rows with a[k:], then get a cell with row[k+1].
>>> [row[k+1] for row in a[k:]]
[2, 7]
a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
k = 0
print(list(list(zip(*a[k:]))[k+1])) # [2, 7]
Is this what you're looking for?
cols = [1,2,3] # extract middle 3 columns
cols123 = [[l[col] for col in cols] for l in a]
# [[2, 3, 4], [7, 8, 9]]

Difference between using list.reverse and list = list[::-1] in python

I'm writing an algorithm that rotates a square matrix 90ยบ degrees in-place, without using a second matrix. It works, but I've got one small problem that is troubling me.
So the basic, working algorithm is:
def rotate(matrix):
n = len(matrix)
# reverse rows
matrix.reverse()
# reflect
start = 0
for row in range(n):
for col in range(start, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
start = start + 1
The idea is to pass a matrix defined as a list of lists, like [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
Example input/output:
>>> some_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> rotate(some_matrix)
>>> print(some_matrix)
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Great. So, I was wondering if I could replace matrix.reverse() with something maybe a little more intuitive, like simply using slice indexing. So I wrote a new rotate, like this:
def rotate2(matrix):
n = len(matrix)
# reverse rows
matrix = matrix[::-1]
# reflect
start = 0
for row in range(n):
for col in range(start, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
start = start + 1
Which SHOULD give me the same results, based on:
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = a
>>> b = b[::-1]
>>> a.reverse()
>>> print(a)
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
>>> print(b)
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
>>> print(a==b)
True
However, when I use rotate2 on the same input/output example, I get:
>>> some_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> rotate2(some_matrix)
>>> print(some_matrix)
[[9, 6, 3], [8, 5, 2], [7, 4, 1]]
So what am I missing here?
matrix = matrix[::-1] creates a new list and assigns it to the local name matrix; it does not modify the original list in-place.
matrix.reverse(), on the other hand, does modify the original list.
Consider these simple functions:
def r1(m):
m = m[::-1]
def r2(m):
m.reverse()
>>> x = [[1,2], [3,4]]
>>> r1()
>>> x
[[1,2], [3,4]]
>>> r2()
>>> x
[[3,4],[1,2]]

multiply all the integers in a list of lists python?

I want to multiply all the values in a list of lists in python:
input = 3*[[1,2,3],[3,2,1]]
so i get this output:
output = [[3,6,9],[9,6,3]]
i tried this:
l = [[1,2,3],[3,2,1]]
l = [i * 2 for i in x in l]
[[ 3 * i for i in inner ] for inner in outer]
>>> my_list = [[1,2,3],[3,2,1]]
>>> [map((3).__mul__, sublist) for sublist in my_list]
[[3, 6, 9], [9, 6, 3]]
You might consider using numpy arrays instead:
>>> import numpy as np
>>> a = np.array(my_list)
>>> a
array([[1, 2, 3],
[3, 2, 1]])
>>> 3*a
array([[3, 6, 9],
[9, 6, 3]])

How to separate last column from 2D-array in Python?

I need to separate 2D array in order to have last column and the rest separately. Those must be arrays both.
Does this help?
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> l = [row[:-1] for row in a]
>>> r = [row[-1] for row in a]
>>> l
[[1, 2], [4, 5], [7, 8]]
>>> r
[3, 6, 9]

Python revert accumulated matrix

I have a matrix like this
[[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
how i get the partial sums by columns in python?
[[1,2,4,6],
[(4-1),(7-2),(9-4),(9-6)],
[(1-4),(9-7),(10-9),(20-9)]]
If you want a solution that doesn't involve numpy, and just uses list of lists and itertools.tee (which is builtin), then the below should work
from itertools import tee
a = [[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
b = []
b.append(a[0])
# Create two iterators and advance one once.
x, y = tee(a)
next(y)
# Iterate over your two iterators and construct a list t which is their difference
# then append this list to b
for i, j in zip(x, y):
t = [h-g for g, h in zip(i,j)]
b.append(t)
print(b)
# [[1, 2, 4, 6],
# [3, 5, 5, 3],
# [-3, 2, 1, 11]]
Try
np.vstack((Z[0],np.diff(Z,axis=0)))
where Z is the matrix you are differentiating.
From the second line, what you want is just the difference of row i and row i-1, and the first line is just the first line of the original array. The easiest way to get this is with numpy. So this works:
In [1]: import numpy as np
In [2]: a = np.array( [[1,2,4,6],
...: [4,7,9,9],
...: [1,9,10,20]]
...: )
In [3]: np.vstack( (a[0], a[1:]-a[:-1]) )
Out[3]:
array([[ 1, 2, 4, 6],
[ 3, 5, 5, 3],
[-3, 2, 1, 11]])
As Lord Henry Wotton (!) points out, the difference a[1:]-a[:-1] is the same as np.diff(a, axis=0).
If you don't want to use numpy or itertools, here is the code
>>> a=[[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> a_r = a[::-1] # reverse original list
>>> for i in range(len(a_r)-1):
... for j in range(len(a_r[0])):
... a_r[i][j] = a_r[i][j] - a_r[i+1][j]
...
>>> a=a_r[::-1] # reverse result
>>> for i in a: print i
[1, 2, 4, 6]
[3, 5, 5, 3]
[-3, 2, 1, 11]
I think this one is nice
>>> a = [[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> c = [[0]*5] ; c.extend(a)
>>> print [[ s-r for r, s in zip(*t)] for t in zip(c[:-1],c[1:])]
[[1, 2, 4, 6], [3, 5, 5, 3], [-3, 2, 1, 11]]
>>>
Here I prepend a list of zeros to the list of lists (obtaining c), and by a bit of packing and unpacking using zip I have a list of lists with the expected results.

Categories

Resources