Converting two lists into a matrix
The standard numpy function for what you want is np.column_stack
:
>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
[2, 5],
[3, 6]])
So with your portfolio
and index
arrays, doing
np.column_stack((portfolio, index))
would yield something like:
[[portfolio_value1, index_value1],
[portfolio_value2, index_value2],
[portfolio_value3, index_value3],
...]
Python: how to combine two flat lists into a 2D array?
list(zip(lat, long))
gives
[(48.01, -6.15), (48.02, -6.1), (48.03, -6.05), (48.04, -6.0),
(48.05, -5.95), (48.06, -5.9), (48.07, -5.85), (48.08, -5.79), (48.1, -5.74)]
More on zip
here
Converting a list of lists into a 2D numpy array
If your lists are NOT of the same length (in each nested dimension) you CANT do a traditional conversion to a NumPy array because it's necessary for a NumPy array of 2D or above to have the same number of elements in its first dimension.
So you cant convert [[1,2],[3,4,5]]
to a numpy array directly. Applying np.array
will give you a 2 element numpy array where each element is a list object as - array([list([1, 2]), list([3, 4, 5])], dtype=object)
. I believe this is the issue you are facing.
You cant create a 2D matrix for example that looks like -
[[1,2,3,?],
[4,5,6,7]]
What you may need to do is pad the elements of each list of lists of lists to a fixed length (equal lengths for each dimension) before converting to a NumPy array.
I would recommend iterating over each of the lists of lists of lists as done in the code I have written below to flatten your data, then transforming it the way you want.
If your lists are of the same length, then should not be a problem with numpy version 1.18.5
or above.
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
np.array(a)
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
However, if you are unable to still work with the list of list of lists, then you may need to iterate over each element first to flatten the list and then change it into a numpy array with the required shape as below -
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
flat_a = [item for sublist in a for subsublist in sublist for item in subsublist]
np.array(flat_a).reshape(2,2,2)
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
Concatenate two lists elementwise to an n x n matrix
Regular Python - using string concatenation and list comprehension:
matrix = [[x + y for x in row] for y in col]
To be compliant with NumPy styling and the desired output use:
np.c_[matrix].T
convert list of lists into matrices
You can use sapply
like:
alpha_out <- t(sapply(theta, function(x) {x$alpha}))
alpha_out <- t(sapply(theta, `[[`, 1))
Convert multiple list variables in to a matrix of desired arrangement
mylist <- list(m1, m2, m3)
#make all vectors the same length
mylist <- lapply(mylist, "length<-", max(lengths(mylist)))
#last observation carried forward
library(zoo)
mylist <- lapply(mylist, na.locf)
#rbind
m <- do.call(rbind, mylist)
# [,1] [,2] [,3]
#[1,] "10" "12" "13"
#[2,] "5" "6" "6"
#[3,] "4" "4" "4"
Print list of lists into matrix format
Try this:
import numpy as np
import pandas as pd
lst = [['1', 'A'],['1', 'B'],['2', 'A'],['2', 'B'],['3', 'A'],['3', 'B']]
def show(lst):
df = pd.DataFrame(lst, columns=['number', 'letter'])
a = []
for x in df['letter'].unique():
a.append(np.array(df[df['letter']==x]))
a = np.array(a)
for i in range(a.shape[1]):
p = ' '.join([str(list(a[j,i])) for j in range(a.shape[0])])
print(p)
show(lst)
Output:
['1', 'A']['1', 'B']
['2', 'A']['2', 'B']
['3', 'A']['3', 'B']
If you have more letters and more rows, then this function will still work.
lst = [['1', 'A'],['1', 'B'],['1', 'C'],['1', 'D'],['1', 'E'],['2', 'A'],['2', 'B'],['2', 'C'],['2', 'D'],['2','E'],['3', 'A'],['3', 'B'],['3', 'C'],['3', 'D'], ['3', 'E'],['4', 'A'],['4', 'B'],['4', 'C'],['4', 'D'], ['4', 'E']]
show(lst)
Output:
['1', 'A'] ['1', 'B'] ['1', 'C'] ['1', 'D'] ['1', 'E']
['2', 'A'] ['2', 'B'] ['2', 'C'] ['2', 'D'] ['2', 'E']
['3', 'A'] ['3', 'B'] ['3', 'C'] ['3', 'D'] ['3', 'E']
['4', 'A'] ['4', 'B'] ['4', 'C'] ['4', 'D'] ['4', 'E']
converting list into a matrix in Python
Maybe what you want is a dict
:
matrix = {
k: {l: 0 for l in res}
for k in res
}
All the values are initialized to 0.
You can easily update values in matrix
; for example, you can increase the value of a 'cell' of one:
matrix['(18,430)']['(19,430)'] += 1
or set it to a specific value:
matrix['(18,430)']['(19,430)'] = 10
and retrieve it:
val = matrix['(18,430)']['(19,430)']
Related Topics
Check If Dataframe Has a Zero Element
How to Skip Blank Line While Reading CSV File Using Python
Python MySQL Connector: Caching_Sha2_Password Plugin
Selenium - Iterating Through Groups of Elements - Python
How to Convert a List of Dictionaries to Json in Python/Django
Efficient Date Range Overlap Calculation
Set Working Directory in Python/Spyder So That It's Reproducible
Blender - How to Add a Color to an Object
Pandas.To_Sql Replace Old Data With New Data Based on 'Unique Id'
Regex to Append Some Characters in a Certain Position
Finding Non-Numeric Rows in Dataframe in Pandas
Hiding Raw_Input() Password Input
Suppress Stdout/Stderr Print from Python Functions
Count Frequency of Words in a List and Sort by Frequency
Is There an Easy Way in Python to Wait Until Certain Condition Is True