Multiply values of two columns per row - python-3.x

I'd like to multiply the values of two columns per row...
from this:
to this:

I think this can be easily done by numpy or pandas. Here is a sample solution-
import pandas as pd
column = ['A','B','C']
dataframe = pd.DataFrame({"A":['a','b','c'],"B":[1,2,3],"C":[2,2,2]})
dataframe['D'] = dataframe['B']*dataframe['C']
print(dataframe)

The answer using pandas is perfectly ok, but to learn Python it is perhaps better to start using the built-in functions first. Here is the answer using lists
my_list = []
my_list.append([1, 2])
my_list.append([2, 2])
my_list.append([3, 2])
print(my_list)
sum_list = []
for element in my_list:
my_sum = element[0] + element[1]
sum_list.append(element + [my_sum])
print(sum_list)
Result
[[1, 2], [2, 2], [3, 2]]
[[1, 2, 3], [2, 2, 4], [3, 2, 5]]
Your exercise to add the first column!

Related

Print multiple columns from a matrix

I have a list of column vectors and I want to print only those column vectors from a matrix.
Note: the list can be of random length, and the indices can also be random.
For instance, the following does what I want:
import numpy as np
column_list = [2,3]
a = np.array([[1,2,6,1],[4,5,8,2],[8,3,5,3],[6,5,4,4],[5,2,8,8]])
new_matrix = []
for i in column_list:
new_matrix.append(a[:,i])
new_matrix = np.array(new_matrix)
new_matrix = new_matrix.transpose()
print(new_matrix)
However, I was wondering if there is a shorter method?
Yes, there's a shorter way. You can pass a list (or numpy array) to an array's indexer. Therefore, you can pass column_list to the columns indexer of a:
>>> a[:, column_list]
array([[6, 1],
[8, 2],
[5, 3],
[4, 4],
[8, 8]])
# This is your new_matrix produced by your original code:
>>> new_matrix
array([[6, 1],
[8, 2],
[5, 3],
[4, 4],
[8, 8]])
>>> np.all(a[:, column_list] == new_matrix)
True

How to create a list of arrays from multiple same-size vectors

I am attempting to create a list of arrays from 2 vectors.
I have a dataset I'm reading from a .csv file and need to pair each value with a 1 to create a list of arrays.
import numpy as np
Data = np.array([1, 2, 3, 4, 5]) #this is actually a column in a .csv file, but simplified it for the example
#do something here
output = ([1,1], [1,2], [1,3], [1,4], [1,5]) #2nd column in each array is the data, first is a 1
I've tried to use numpy concatenate and vstack, but they don't give me exactly what I'm looking for.
Any suggestions would be appreciated.
You can form the output using a list comprehension:
data = [1, 2, 3, 4, 5]
output = [[1, item] for item in data]
This will output:
[[1, 1], [1, 2], [1, 3], [1, 4], [1, 5]]

How to get combination from 2 list by taking 1 element from list1 and rest of the element from list2 and so on in python

list1 = [1,1,2,4]
list2 = [2,3,5,6]
i would like get all combination like [1,3,5,6], [1,3,5,6] like all combination in python
My question is like list1=[1,2,3,4] list2=[5,6,7,8] I need to see the lists like [1,5,6,7] [5,2,7,8] meaning all possible combination of 2 list.please help
Like this IIUC:
>>> print([[i] + list2[1:] for i in list1])
[[1, 3, 5, 6], [1, 3, 5, 6], [2, 3, 5, 6], [4, 3, 5, 6]]
I think this is what you are looking for:
import itertools
list1 = [1,1,2,4]
list2 = [2,3,5,6]
combination_list = list(itertools.combinations(list1 + list2, 4))
this joins the two lists into one list (i.e, [1,1,2,4,2,3,5,6]) and takes all the 4 element combinations.

I'm trying to add lists in lists by column. Is there a way to sum them with missing variables in a list?

I had followed the book and can sum lists in lists by column but one of the test cases is missing variables in the list and I'm unable to move forward because I keep getting an index error.
The first initial_list works as it should giving [3,6,9]
The second one though should apparently give me [3,4,9,4]
list_initial = [[1, 2, 3], [1, 2, 3],[1, 2, 3 ]]
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
def column_sums(list_initial):
column = 0
list_new = []
while column < len(list_initial):
total = sum(row[column] for row in list_initial )
list_new.append(total)
column = column + 1
print(list_new)
column_sums(list_initial)
You can effectively "transpose" your data so that rows become columns, and then use itertools.zip_longest with a fillvalue of 0, to sum across them, eg:
from itertools import zip_longest
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
summed = [sum(col) for col in zip_longest(*list_initial, fillvalue=0)]
# [3, 4, 6, 4]

Summing two 2-D lists

so this has kind of stumped me. I feel like it should be an easy problem though.
Lets say I have these two lists
a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]
I am trying so it would return the sum of the two 2-D lists of each corresponding element like so
c = [[4, 6], [8, 11]]
I am pretty sure I am getting lost in loops. I am only trying to use nested loops to produce an answer, any suggestions? I'm trying several different things so my code is not exactly complete or set in stone and will probably change by the time someone reponds so I won't leave a code here. I am trying though!
You could try some variation on nested for-loops using enumerate (which will give you the appropriate indices for comparison to some other 2d array):
a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]
Edit: I didn't see you wanted to populate a new list, so I put that in there:
>>> c = []
>>> for val, item in enumerate(a):
newvals = []
for itemval, insideitem in enumerate(item):
newvals.append(insideitem + b[val][itemval])
c.append(newvals)
newvals = []
Result:
>>> c
[[4, 6], [8, 11]]
Use numpy:
import numpy as np
a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]
c = np.array((a,b))
np.sum(c, axis=0)
I know it is an old question, but following nested loops code works exactly as desired by OP:
sumlist = []
for i, aa in enumerate(a):
for j, bb in enumerate(b):
if i == j:
templist = []
for k in range(2):
templist.append(aa[k]+bb[k])
sumlist.append(templist)
templist = []
print(sumlist)
Output:
[[4, 6], [8, 11]]

Resources