Python: Numpy accumulated list not seperated by commas - python

Simple example: I got a list called 'mylist' and I want to accumulate the numbers inside and save them into a new list called 'mylist_accum'.
import numpy
mylist = [1,2,3,4,5]
print mylist
mylist_accum = numpy.add.accumulate(mylist)
print mylist_accum
My prints look like this:
[1, 2, 3, 4, 5]
[ 1 3 6 10 15]
And I want them to look like this:
[1, 2, 3, 4, 5]
[1, 3, 6, 10, 15]
I need my accumulated listelements to be seperated by commas. Otherwise Matplotlib cant work with them.

It's just printing, matplotlib could handle with the numpy.arrays easy:
In [77]: type(mylist_accum)
Out[77]: numpy.ndarray
If you want to see with commas you could use .tolist method of the numpy.array:
In [75]: mylist_accum.tolist()
Out[75]: [1, 3, 6, 10, 15]
Or convert it to usual list:
In [74]: list(mylist_accum)
Out[74]: [1, 3, 6, 10, 15]

Related

Converting elements of a list to a string and then iteratively listing each element in a text file

Consider this simple example
Suppose that we have the following list:
[[2, 3, 4], [5, 6, 7], [8, 9, 10]]
I would like to write each list in this list as a separate line in a text file. i.e...
2 3 4
5 6 7
8 9 10
To do that, I seems that you must convert each element to a string because object.write() expects a string (is there a better way to do this?). Now, for a single list like [2, 3, 4], I have been doing the following:
l = [2, 3, 4]
s = ' '.join(str(x) for x in l)
with open("file_open.txt", "+a") as file_object:
file_object.write("\n")
file_object.write(str(s))
How do I do this for a more complicated list like [[2, 3, 4], [5, 6, 7], [8, 9, 10]] where each element is iteratively listed in a text file as
2 3 4
5 6 7
8 9 10
Note: in the actual case that I am dealing with, it was originally a numpy array that I converted to a list, and it has the form
[[[1.5, 7.912834397348988, 148.46579073169295]], [[2.0, 7.912834397348988, 148.46579073169295]],...]]]
Like in the simple example that I gave, I need a text file in the form
1.5, 7.912834397348988, 148.46579073169295
2.0, 7.912834397348988, 148.46579073169295
It does not have to be a list. Would be be easier to keep it as a numpy array?
You could use numpy.savetxt to do this
import numpy as np
data = np.array([[2, 3, 4], [5, 6, 7], [8, 9, 10]])
np.savetxt('file_open.txt', data)
The default delimiter is ' ' and newline is '\n' but you can pass those arguments if you prefer something else.
If you were to write this by hand, it would look something like
data = [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
with open('file_open.txt') as f_out:
for line in data:
f_out.write(' '.join(str(i) for i in line) + '\n')

Function is kicking out variable with 3, separate lists

For the program I am writing my goal is to call a function, give it 2 values and then have it spit back lists based on those 2 numbers. Here's what I have so far,
import numpy as np
def list_maker (n, m):
for n in range(n):
l = list(np.random.randint(1,9, m))
print(l)
My goal is to type "list_maker(3,5)" and have it output 3 lists, each with 5 elements. I want to keep using numpy so I can learn more about it rather than another type of operation. Whenever I call the function my out it,
list_maker(3,5)
[2, 7, 1, 5, 6]
[8, 5, 1, 3, 5]
[8, 2, 6, 3, 7]
However, I can not specifically change one element in one list, if I do l[0] = "Blank", all the elements at 0 position turn to blank and I can't do [0],[1]....
Any idea how to get an output like,
list_maker(3,5)
[[2, 7, 1, 5, 6],
[8, 5, 1, 3, 5],
[8, 2, 6, 3, 7]]
Where I can then specifically edit one element in one of the lists done by numpy?
Thank you for all the replies!
you want to return a list of lists. A simple list comprehension would work:
import numpy as np
def list_maker (n, m):
return [list(np.random.randint(1,9, m)) for _ in range(n)]
then:
>>> list_maker(3,5)
[[1, 7, 2, 5, 7], [3, 5, 5, 7, 7], [8, 5, 1, 1, 1]]
At the moment your function is just printing the lists and not returning them.
And I'm not entirely sure of your intent; at the moment you're not creating a numpy array, but a list. More specifically, you're creating a list of 3 lists, not 3 separate lists.
You could create a numpy array by passing the n, m values directly to numpy's randint:
np.random.randint(1,9, size=(n, m))

How can I split a list into a list of lists based on the difference between adjacent elements?

E.g., if I've got
MAX_ALLOWED_DIFF = 3
nums=[1, 2, 4, 10, 13, 2, 5, 5, 5]
the output should be
groups = [[1, 2, 4], [10, 13], [2, 5, 5, 5]]
The context: I had a pandas.Series object nums and I used
nums = nums.diff().gt(DETECTION_MAX_DIFF_NS).cumsum()).apply(list).tolist()
to subsample in the same fashion but I noticed that there're a lot of duplicates in my Series nums and after I use .unique() method I don't have Series object anymore, I've got numpy.ndarray (1D) instead.
I believe I may use sth like pandas.Series(nums.unique) but I don't like this hack.
So we using drop_duplicates, keep nums stay in pd.Series
nums=nums.drop_duplicates()
nums.groupby(nums.diff().abs().gt(MAX_ALLOWED_DIFF).cumsum()).apply(list).tolist()
Out[447]: [[1, 2, 4], [10, 13], [5]]
Here's one approach -
>>> import numpy as np
>>> idx = np.r_[0,np.flatnonzero(np.abs(np.diff(nums))>MAX_ALLOWED_DIFF)+1,len(nums)]
>>> [nums[i:j] for (i,j) in zip(idx[:-1],idx[1:])]
[[1, 2, 4], [10, 13], [2, 5, 5, 5]]
Given that you've tagged with numpy too, here's one way to do it:
thr = 3
ix = np.flatnonzero(np.concatenate([[False], np.abs(np.diff(nums))>thr]))
np.split(nums, ix)
Output
[array([1, 2, 4]), array([10, 13]), array([2, 5, 5, 5])]

Need Help in switching values in a list in python

I have a list of numbers, such as:
[1, 2, 3, 4, 5, 6]
I'm having trouble figuring out how to switch the first 2 items of the list with the last 2, or the first 3 with the last 3, and so on.
When i assign the values of the 1st two numbers to the last 2 items of the list, i then cannot assign the last 2 values (what used to be the last 2 values of the list) to the first two because the last 2 values have been lost.
If i try using another empty list and appending the last 2 values of the original list to that list, then appending the middle values, and then the first 2 values of the old list, I end up with something like this:
[[[5, 6], [3, 4], [1, 2]]]
I don't want nested lists! What I want is:
[5, 6, 3, 4, 1, 2]
Can someone help me?
>>> nums = [1, 2, 3, 4, 5, 6]
>>> nums[:2], nums[-2:] = nums[-2:], nums[:2]
>>> nums
[5, 6, 3, 4, 1, 2]
This modifies the original list but if you want a separate new list you should use the following:
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swapped_nums = nums[-2:] + nums[2:-2] + nums[:2]
>>> swapped_nums
[5, 6, 3, 4, 1, 2]
Note: This won't work properly if your list has < 4 elements

how to create a list of lists

My Python code generates a list everytime it loops:
list = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
But I want to save each one - I need a list of lists right?
So I tried:
list[i] = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
But Python now tells me that "list" is not defined. I'm not sure how I go about defining it. Also, is a list of lists the same as an array??
Thank you!
You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:
>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]
Create your list before your loop, else it will be created at each loop.
>>> list1 = []
>>> for i in range(10) :
... list1.append( range(i,10) )
...
>>> list1
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]]
Use append method, eg:
lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)
First of all do not use list as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.
The first can be referenced with my_list[0] and the second with my_list[1]
Just came across the same issue today...
In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:
list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

Categories

Resources