import random
ROWS = 3
COLS = 3
def main():
values = [[0,0,0], [0,0,0], [0,0,0]]
for r in range(ROWS):
for c in range(COLS):
values[r][c] = random.randint(1, 4)
print('List:')
print(values)
print(sum(values[0]))
print(sum(values[1]))
print(sum(values[2]))
main()
This is the code that I have written and what I would like to do is display the the individual totals for each column. For example, the final result would look like:
Total of column 0 is 7
Total of column 1 is 6
Total of column 2 is 7
Builtin python lists are not very ideal for working with matrix-like data. I would highly suggest using numpy:
import numpy as np
l = np.array(values)
l.sum(axis=1)
However, if you really need to use python lists, one strategy is just to reduce your outer list with your desired output.
reducer = lambda x, y : [x[i] + y[i] for i in range(len(x)]
reduce(reducer, values)
You can simply reverse the order of ROWS and COLS in another pair of nested loops:
import random
ROWS = 3
COLS = 3
values = list()
for r in range(ROWS):
values.append(list())
for c in range(COLS):
values[r].append(random.randint(1, 4))
print('List:', values, sep="\n")
for c in range(COLS):
sum = 0
for r in range(ROWS):
sum += values[r][c]
print("Total of column {} is {}".format(c, sum))
Produces:
List:
[[3, 2, 4], [4, 3, 4], [4, 2, 3]]
Total of column 0 is 11
Total of column 1 is 7
Total of column 2 is 11
You can try :
import random
ROWS=3
COLS=3
def main():
values = []
for i in range(ROWS):
list1=[]
for j in range(COLS):
val =random.randint(1,4)
list1.append(val)
values.append(list1)
print (values)
for col in range(COLS):
sum = 0
for row in range(ROWS):
sum += values[row][col]
print("Total of column "+str(col)+" is " +str(sum))
main()
[[4, 1, 2], [2, 3, 4], [3, 3, 1]]
Total of column 0 is 9
Total of column 1 is 7
Total of column 2 is 7
I ended up using something which now seems quite simple:
thank you for your responses
values = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for r in range(ROWS):
for c in range(COLS):
values[r][c] = random.randint(1, 4)
print('List:')
print(values)
print('Total of row 0 is', sum(values[0]))
print('Total of row 1 is', sum(values[1]))
print('Total of row 2 is', sum(values[2]))
valuescolumn1 = [row[0] for row in values]
print('Total of column 0 is', sum(valuescolumn1))
valuescolumn2 = [row[1] for row in values]
print('Total of column 1 is', sum(valuescolumn2))
valuescolumn3 = [row[1] for row in values]
print('Total of column 2 is', sum(valuescolumn3))
Related
I have n rows and m columns I need a matrix which consists of consecutive m numbers like 1,2,3,4 this in each of the n rows that needs to be in ever increasing order.
example: 3 X 4 matrix\
**[\
[1, 2, 3, 4], \
[5, 6, 7, 8],\
[9, 10, 11, 12]\
]**
The intuition is very simple. What we need is our starting element in eaxh row should be the next element of the previous row's last element. That is the only tricky part in this problem.
For that we start our next row generation with arr[i-1][-1] to the arr[i-1][-1] + m. But for the first row generation we start from 1 since the matrix is empty.
Code
mat = []
n,m = map(int,input().split())
for row in range(n):
# if the row is starting row we start it with 1
# Else we assign k to the prev rows
if row == 0:
k = 1
else:
k = mat[row-1][-1] + 1
x = []
#the new row starts from previous rows last elemnt + 1
for j in range(k,k+m):
x.append(j)
mat.append(x)
print(mat)
First generate a continuous sequence of numbers and then adjust the format, with reference to either:(n and m represent the number of rows and columns respectively)
use the built-in functions, array to generate sequences, reshape to adjust the layout
import numpy as np
n, m = map(int, input().split())
res = np.arange(1, n*m+1).reshape(n, m)
print(res)
using list generative
items = list(range(1, m*n+1))
res = [items[i:i+m] for i in range(0, len(items), m)]
print(res)
here's a one liner to achieve that -
row, col = 3, 4
mat = [[col*i + j for j in range(1, col+1)] for i in range(row)]
print(mat)
I would like to print sum of each row and sum of each column of a two dimensional array, like this:
sum row1 = 123 (numbers are not real sums, just for example)
sum row2 = 123
sum row3 = 123
And the same with columns. I know how to do it in java, but dont know how to do it in python.
This is my code(missing code for sums of rows and columns, because I dont know how to do it):
from random import randint
dim1 = input("Insert first dimension: ")
dim1 = int(dim1)
dim2 = input("Insert second dimension: ")
dim2 = int(dim2)
table1d = []
for i in range(dim1):
table2d = []
for j in range(dim2):
table2d.append(randint(1, 170))
table1d.append(table2d)
print(table1d)
totalSum = sum(map(sum, table1d))
print(totalSum)
sumRows = 0
for i in range(0, len(table1d), 1):
sumRows += table1d[i]
For rows you need only
sums_in_rows = list(map(sum, table1d))
print(sums_in_rows)
For columns it needs more
sums_in_columns = [0]*len(table1d[0]) # create list for all results
for row in table1d:
for c, value in enumerate(row):
sums_in_columns[c] += value
print(sums_in_columns)
You can also convert it to numpy array and then you have
import numpy as np
arr = np.array(table1d)
print('rows:', arr.sum(axis=1))
print('cols:', arr.sum(axis=0))
print('total:', arr.sum())
from random import randint
dim1 = input("Insert first dimension: ")
dim1 = int(dim1)
dim2 = input("Insert second dimension: ")
dim2 = int(dim2)
table1d = []
#x = 0
for i in range(dim1):
table2d = []
for j in range(dim2):
table2d.append(randint(1, 170))
#table2d.append(x)
#x += 1
table1d.append(table2d)
print(table1d)
sums_in_rows = list(map(sum, table1d))
print(sums_in_rows)
sums_in_columns = [0]*len(table1d[0])
for row in table1d:
for c, value in enumerate(row):
sums_in_columns[c] += value
print(sums_in_columns)
import numpy as np
arr = np.array(table1d)
print(arr.sum(axis=1))
print(arr.sum(axis=0))
print(arr.sum())
import numpy as np
Columns:
np.array(table1d).sum(axis=0)
Rows:
np.array(table1d).sum(axis=1)
You can use list comprehensions and the sum function to obtain the desired result:
import random
rowCount = 3
colCount = 5
matrix = [ [random.randint(10,99) for _ in range(colCount)] for _ in range(rowCount) ]
for line in matrix:
print(line)
for row in range(rowCount):
print(f"sum row{row} = ",sum(matrix[row]))
for col in range(colCount):
print(f"sum column{col} = ",sum(row[col] for row in matrix))
[90, 62, 86, 19, 13]
[33, 93, 38, 17, 29]
[11, 96, 91, 66, 81]
sum row0 = 270
sum row1 = 210
sum row2 = 345
sum column0 = 134
sum column1 = 251
sum column2 = 215
sum column3 = 102
sum column4 = 123
Here is a simple and straightforward two-loop solution, if you want to do both the sums together.
container = [[1, 2, 3, 4],
[3, 2, 1, 5],
[4, 5, 6, 6]]
rowSum, colSum, i = [0]*len(container), [0]*len(container[0]), 0
while i < len(container):
j = 0
while j < len(container[0]):
rowSum[i] += container[i][j]
colSum[j] += container[i][j]
j += 1
i += 1
print(rowSum, colSum)
Hope it helps. ✌
I need to select each time N rows in a pandas Dataframe using iterrows.
Something like this:
def func():
selected = []
for i in range(N):
selected.append(next(dataframe.iterrows()))
yield selected
But doing this selected has N equal elements. And each time I call func I have always the same result (the first element of the dataframe).
If the dataframe is:
A B C
0 5 8 2
1 1 2 3
2 4 5 6
3 7 8 9
4 0 1 2
5 3 4 5
6 7 8 6
7 1 2 3
What I want to obtain is:
N = 3
selected = [ [5,8,2], [1,2,3], [4,5,6] ]
then, calling again the function,
selected = [ [7,8,9], [0,1,2], [3,4,5] ]
then,
selected = [ [7,8,6], [1,2,3], [5,8,2] ]
No need for .iterrows(), rather use slicing:
def flow_from_df(dataframe: pd.DataFrame, chunk_size: int = 10):
for start_row in range(0, dataframe.shape[0], chunk_size):
end_row = min(start_row + chunk_size, dataframe.shape[0])
yield dataframe.iloc[start_row:end_row, :]
To use it:
get_chunk = flow_from_df(dataframe)
chunk1 = next(get_chunk)
chunk2 = next(get_chunk)
Or not using a generator:
def get_chunk(dataframe: pd.DataFrame, chunk_size: int, start_row: int = 0) -> pd.DataFrame:
end_row = min(start_row + chunk_size, dataframe.shape[0])
return dataframe.iloc[start_row:end_row, :]
I am assuming you are calling the function in a loop. You can try this.
def select_in_df(start, end):
selected = data_frame[start:end]
selected = select.values.tolist()
return selected
print(select_in_df(0, 4)) #to update the start and end values, you can use any loop or whatever is your convenience
#here is an example
start = 0
end = 3
for i in range(10): #instead of range you can use data_frame.iterrows()
select_in_df(start, end+1) #0:4 which gives you 3 rows
start = end+1
end = i
return should be used instead of yield. if you want plain data in selected as list of list you can do this:
def func():
selected = []
for index, row in df.iterrows():
if(index<N):
rowData =[]
rowData.append(row['A'])
rowData.append(row['B'])
rowData.append(row['C'])
selected.append(rowData)
else:
break
return selected
I think I found an answer, doing this
def func(rowws = df.iterrows(), N=3):
selected = []
for i in range(N):
selected.append(next(rowws))
yield selected
selected = next(func())
Try using:
def func(dataframe, N=3):
return np.array_split(dataframe.values, N)
print(func(dataframe))
Output:
[array([[5, 8, 2],
[1, 2, 3],
[4, 5, 6]]), array([[7, 8, 9],
[0, 1, 2],
[3, 4, 5]]), array([[7, 8, 6],
[1, 2, 3]])]
I am trying to write a function that adds all elements in a matrix. The special condition is if an element in the matrix is 0, we count the element below this 0 also 0. For example:
matrix =
[[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
Should return 9 because 1+1+2+5=9
Here is what I have for my code, I got this error, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Can someone please help?
import numpy as np
def matrixElementsSum(matrix):
a=np.array([matrix])
sumofcolumn=0
sum=0
for x in range(len(a)): # x in matrix row
for y in range(len(a[0])): #y in matrix col
if a[x][y]==0:
a[x+1][y]==0 #set next row same column=0
sumofcolumn+=a[x][y] #sumofcolumn is a column sum
for x in sumofcolumn:
sum+=x
return sum
You could rotate, flatten, and them use a simple comprehension:
import numpy as np
matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
matrix = np.rot90(matrix).flatten()
indices = set(np.where(matrix==0)[0]+1) # set of indices to the right of 0 fast lookup
final = sum(e for i,e in enumerate(matrix) if i not in indices)
print(final)
Output:
9
When you rotate and flatten, you are left with:
[2 0 3 1 0 3 1 5 0 0 0 2]
And if you notice, all the values that had 0 above them in your matrix, now have 0 to the left of them, and you can use the list comprehension to ignore these, and then find the sum of the result.
I'm sure there is a way to do this without the rotation, but I feel this way is much easier to visualize.
Find the woking code with inline comments where you got wrong.
import numpy as np
def matrixElementsSum(matrix):
a = np.array(matrix) # no need of appending in []
my_sum = 0 # sumofcolumn not required
for x in range(len(a)): # x in matrix row
for y in range(len(a[x])): # y in matrix col
if a[x][y] == 0 and x < len(a)-1: # handling last index
a[x+1][y] = 0 # set next row same column=0
my_sum += a[x][y] # adding value to sum..
# no for loop required, you are not appending values to a list.
# it's an integer and it's declared outside of loops.
return my_sum
matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
print(matrix)
print(matrixElementsSum(matrix))
You can do this as follows
total = 0
zeros = []
for row in matrix:
total += sum([val for ix, val in enumerate(row) if not ix in zeros])
zeros = [ix for ix, i in enumerate(row) if i == 0]
total
It can be done with rows-to-columns and flat list where index is increased by 2 if value is 0:
def matrix_elements_sum(matrix):
lst = sum(list(zip(*matrix)), ()) # rows-to-columns and to flat list
total = 0
i = 0
while i < len(lst):
if lst[i] != 0:
total += lst[i]
i += 1
else:
i += 2
return total
def matrixElementsSum(matrix):
totalSum = 0
for row in range(len(matrix)):
for col in range (len(matrix[0])):
if matrix[row][col] == 0 and row != len(matrix) -1:
matrix[row+1][col] = 0
else:
totalSum = totalSum + matrix[row][col]
return totalSum
I know this is vary late...
def matrixElementsSum(matrix):
sum = 0
for r in range(len(matrix)):
for c in range(len(matrix[r])):
if (matrix[r][c] != 0):
if (r==0):
sum += matrix[r][c]
else:
if(matrix[r-1][c] !=0):
sum += matrix[r][c]
else:
if(r == len(matrix)-1):
continue
else:
matrix[r+1][c] = 0
return sum
I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.
Perhaps you can help me to find what is wrong with my code.
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the number of columns
for j in range (0,n):
columns += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = columns
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
The problem is on the initialization step.
for i in range (0,m):
matrix[i] = columns
This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:
>>> for i in range (0,m):
... matrix[i] = columns
...
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]
You can initialize your matrix in a nested loop, like this:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
or, in a one-liner by using list comprehension:
matrix = [[0 for j in range(n)] for i in range(m)]
or:
matrix = [x[:] for x in [[0]*n]*m]
See also:
How to initialize a two-dimensional array in Python?
Hope that helps.
you can accept a 2D list in python this way ...
simply
arr2d = [[j for j in input().strip()] for i in range(n)]
# n is no of rows
for characters
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = list(input().strip())
print(a)
or
n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
a[i].append(list(input().strip()))
print(a)
for numbers
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = [int(j) for j in input().strip().split(" ")]
print(a)
where n is no of elements in columns while m is no of elements in a row.
In pythonic way, this will create a list of list
If the input is formatted like this,
1 2 3
4 5 6
7 8 9
a one liner can be used
mat = [list(map(int,input().split())) for i in range(row)]
explanation with example:
input() takes a string as input. "1 2 3"
split() splits the string by whitespaces and returns a
list of strings. ["1", "2", "3"]
list(map(int, ...)) transforms/maps the list of strings into a list of ints. [1, 2, 3]
All these steps are done row times and these lists are stored in another list.[[1, 2, 3], [4, 5, 6], [7, 8, 9]], row = 3
If you want to take n lines of input where each line contains m space separated integers like:
1 2 3
4 5 6
7 8 9
Then you can use:
a=[] // declaration
for i in range(0,n): //where n is the no. of lines you want
a.append([int(j) for j in input().split()]) // for taking m space separated integers as input
Then print whatever you want like for the above input:
print(a[1][1])
O/P would be 5 for 0 based indexing
Apart from the accepted answer, you can also initialise your rows in the following manner -
matrix[i] = [0]*n
Therefore, the following piece of code will work -
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
This code takes number of row and column from user then takes elements and displays as a matrix.
m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
b = []
print("{0} Row".format(i))
for j in range(1,n+1):
b.append(int(input("{0} Column: " .format(j))))
a.append(b)
print(a)
If your matrix is given in row manner like below, where size is s*s here s=5
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
then you can use this
s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]
your matrix will be 'arr'
m,n=map(int,input().split()) # m - number of rows; n - number of columns;
matrix = [[int(j) for j in input().split()[:n]] for i in range(m)]
for i in matrix:print(i)
no_of_rows = 3 # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)
You can make any dimension of list
list=[]
n= int(input())
for i in range(0,n) :
#num = input()
list.append(input().split())
print(list)
output:
Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:
rows = int(input('Number of rows: '))
cols = int(input('Number of columns: '))
matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]
with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.
a = []
b = []
m=input("enter no of rows: ")
n=input("enter no of coloumns: ")
for i in range(n):
a = []
for j in range(m):
a.append(input())
b.append(a)
Input : 1 2 3 4 5 6 7 8 9
Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]
row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
print('value of i: ',i)
a=list(map(int,input().split()))
print(a)
b.append(a)
print(b)
print(row)
Output:
2 3
value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i: 1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]
Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2 so be careful. This is not the code where you can control no of columns.
a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
for j in range(n):
b.append(int(input()))
a.append(b)
print("Here your {} column {}".format(i+1,a))
b=[]
for m in range(n):
print(a[m])
works perfectly
rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
a=list(map(int,input().split()))
b.append(a)
print(b)
input
2 3
1 2 3
4 5 6
output
[[1, 2, 3], [4, 5, 6]]
I used numpy library and it works fine for me. Its just a single line and easy to understand.
The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix.
Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.
import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)
print(a)
Input
array([[1, 2],
[3, 4]])
Output