I have a feeling that this is very easy but I can't quite figure out how to do it. Say I have a Numpy array
[1,2,3,4]
How do I convert this to
[[1],[2],[3],[4]]
In an easy way?
Thanks
You can use np.newaxis:
>>> a = np.array([1,2,3,4]
array([1, 2, 3, 4])
>>> a[:,np.newaxis]
array([[1],
[2],
[3],
[4]])
You can use numpy.reshape:
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> np.reshape(a, (-1, 1))
array([[1],
[2],
[3],
[4]])
If you want normal python list then use list comprehension:
>>> a = np.array([1,2,3,4])
>>> [[x] for x in a]
[[1], [2], [3], [4]]
The most obvious way that comes to mind is:
>>> new = []
>>> for m in a:
new.append([m])
but this creates normal Python's list of lists, I'm not sure if this is what you want...
>>> A = [1,2,3,4]
>>> B = [[x] for x in A]
>>> print B
[[1], [2], [3], [4]]
Related
np_array_a = np.array([[1,2], [3,4], [5,0]]) # can have any number of rows but 2 columns
np_array_b = np.array([[5,6], [7,8], [5,0]]) # can have any number of rows but 2 columns
dct={"a": np_array_a, "b": np_array_b}
I want to extract the inner numpy elements from the dct and make a new numpy array. For example, for python list I can use * operator to extract elements. I know I can iterate through the dct and achieve it but was wondering if there is any numpy way of doing it?
New numpy array should be of the following form:
new_np_array = np.array([[1,2], [3,4], [5,0],[5,6], [7,8], [5,0]])
You can use indexing:
a[0]
#[1,2]
and
a[1]
#[3,4]
I would use list comprehension:
extract = [item for nested_list in np_array for item in nested_list]
new_array = np.concatenate(list(dct.values()))
Result:
array([[1, 2],
[3, 4],
[5, 0],
[5, 6],
[7, 8],
[5, 0]])
I would simply use vstack:
np.vstack([np_array_a,np_array_b])
My question is as follows:
I have some lists such as [1], [1,2], [1,3,1], and I want to put them in a 2D array result, which is [[1],[1,2],[1,3,1]]. Are there any simple ways to do that? Thanks.
yea, there are
l1, l2, l3=[1], [1,2], [1,3,1]
biglist=[l1,l2,l3]
Try this:
l1 = [1]
l2 = [1, 2]
l3 = [1, 3, 1]
result = []
result.append(l1)
result.append(l2)
result.append(l3)
print(result)
Or you can write shorter:
l1 = [1]
l2 = [1, 2]
l3 = [1, 3, 1]
result = [l1,l2,l3]
print(result)
output:
[[1], [1, 2], [1, 3, 1]]
While I don't think there is something exactly the same as a 2D Array, you can just put those lists in a 2D list (as SuperStew shows):
a = [1]
b = [1,2]
c = [1,3,1]
d = [a,b,c]
Now, you can call d like you would a 2D Array. For Example:
print d[0][0]
print d[2][1]
Returns:
1
3
There you go:
x, y, z = [1], [1,2], [1,3,1]
[x,y,z]
I am attempting to merge two python lists, where their values at a given index will form a list (element) in a new list. For example:
merge_lists([1,2,3,4], [1,5]) = [[1,1], [2,5], [3], [4]]
I could iterate on this function to combine ever more lists. What is the most efficient way to accomplish this?
Edit (part 2)
Upon testing the answer I had previously selected, I realized I had additional criteria and a more general problem. I would also like to combine lists containing lists or values. For example:
merge_lists([[1,2],[1]] , [3,4]) = [[1,2,3], [1,4]]
The answers currently provided generate lists of higher dimensions in cases like this.
One option is to use itertools.zip_longest (in python 3):
from itertools import zip_longest
[[x for x in t if x is not None] for t in zip_longest([1,2,3,4], [1,5])]
# [[1, 1], [2, 5], [3], [4]]
If you prefer sets:
[{x for x in t if x is not None} for t in zip_longest([1,2,3,4], [1,5])]
# [{1}, {2, 5}, {3}, {4}]
In python 2, use itertools.izip_longest:
from itertools import izip_longest
[[x for x in t if x is not None] for t in izip_longest([1,2,3,4], [1,5])]
#[[1, 1], [2, 5], [3], [4]]
Update to handle the slightly more complicated case:
def flatten(lst):
result = []
for s in lst:
if isinstance(s, list):
result.extend(s)
else:
result.append(s)
return result
This handles the above two cases pretty well:
[flatten(x for x in t if x is not None) for t in izip_longest([1,2,3,4], [1,5])]
# [[1, 1], [2, 5], [3], [4]]
[flatten(x for x in t if x is not None) for t in izip_longest([[1,2],[1]] , [3,4])]
# [[1, 2, 3], [1, 4]]
Note even though this works for the above two cases, but it can still break under deeper nested structure, since the case can get complicated very quickly. For a more general solution, you can see here.
Another way to have your desired output using zip():
def merge(a, b):
m = min(len(a), len(b))
sub = []
for k,v in zip(a,b):
sub.append([k, v])
return sub + list([k] for k in a[m:]) if len(a) > len(b) else sub + list([k] for k in b[m:])
a = [1, 2, 3, 4]
b = [1, 5]
print(merge(a, b))
>>> [[1, 1], [2, 5], [3], [4]]
You could use itertools.izip_longest and filter():
>>> lst1, lst2 = [1, 2, 3, 4], [1, 5]
>>> from itertools import izip_longest
>>> [list(filter(None, x)) for x in izip_longest(lst1, lst2)]
[[1, 1], [2, 5], [3], [4]]
How it works: izip_longest() aggregates the elements from two lists, filling missing values with Nones, which you then filter out with filter().
Another way using zip_longest and chain from itertools:
import itertools
[i for i in list(itertools.chain(*itertools.zip_longest(list1, list2, list3))) if i is not None]
or in 2 lines (more readable):
merged_list = list(itertools.chain(*itertools.zip_longest(a, b, c)))
merged_list = [i for i in merged_list if i is not None]
I have a python array that looks like this: [1, 2, 3, 4, 5]
I want it to look like this: [[1], [2], [3], [4], [5]]
How do I go about doing this?
Thanks!
I assume you are talking about lists. This should work:
l = [1, 2, 3, 4, 5]
out = [[i] for i in l]
You can also do it like this using append method of list
list_a = [1,2,3,4,5]
new_list = []
for i in list_a:
new_list.append([i])
Is there a way to get an alias for a part of a list in python?
Specifically, I want the equivalent of this to happen:
>>> l=[1,2,3,4,5]
>>> a=l
>>> l[0]=10
>>> a
[10, 2, 3, 4, 5]
But what I get is this:
>>> l=[1,2,3,4,5]
>>> a=l[0:2]
>>> l[0]=10
>>> a
[1, 2]
If numpy is an option:
import numpy as np
l = np.array(l)
a = l[:2]
l[0] = 10
print(l)
print(a)
Output:
[10 2 3 4 5]
[10 2]
slicing with basic indexing returns a view object with numpy so any change are reflected in the view object
Or use a memoryview with an array.array:
from array import array
l = memoryview(array("l", [1, 2, 3, 4,5]))
a = l[:2]
l[0]= 10
print(l.tolist())
print(a.tolist())
Output:
[10, 2, 3, 4, 5]
[10, 2]
You could embed each element into its own mutable data structure (like a list).
>>> l=[1,2,3,4,5]
>>> l = [[item] for item in l]
>>> l
[[1], [2], [3], [4], [5]]
>>> a = l[:2]
>>> a
[[1], [2]]
>>> l[0][0] = 10
>>> l
[[10], [2], [3], [4], [5]]
>>> a
[[10], [2]]
However, I recommend trying to come up with a solution to your original issue (whatever that was) that doesn't create issues of its own.
What you're looking for is a view of the original list, so that any modifications are reflected in the original list. This is doable with the array in the numpy package:
>>> import numpy
>>> x = numpy.array([1, 2, 3])
>>> y = x[2:]
>>> y[0] = 999
>>> x
array([ 1, 2, 999])