eliminate selected column of elements from a list of lists - list

I have a list of lists where each individual list has 3 elements. Something like this:
[[928.7, 554.29999958311, 0],
[928.7, 558.15990063549, 0],
[914.1, 558.15990063549, 0],
[914.1, 554.29999958311, 0]]
How can I delete all the elements from a particular column? For example if I input "1" that will delete the first column, if I input "2" it will delete the second one and so on.

I assume your question regards pyhton...
I would try something like the following (using numpy):
import numpy as np
initial_list = [[928.7, 554.29999958311, 0],
[928.7, 558.15990063549, 0],
[914.1, 558.15990063549, 0],
[914.1, 554.29999958311, 0]]
# transform the list in a numpy array
a = np.array(initial_list)
# remove the column you want and put the output in a new variable
a1 = np.delete(a, 0, 1) # this would the remove the first column(0)
#+the second "1" in the arguments tells to
#+numpy to delete the column instead of the
#+ row.
# convert back to a plain list
final_list = a1.tolist()
If you want to stay with plain python, I would suggest something like:
initial_list = [[928.7, 554.29999958311, 0],
[928.7, 558.15990063549, 0],
[914.1, 558.15990063549, 0],
[914.1, 554.29999958311, 0]]
for row in initial_list:
del row[0] # This would delete the first column from your matrix
final_list = initial_list
Pay attention to the fact that the latter method will "overwrite" the original list and you will loose all the deleted data. Consider, if you need, to create a copy of the initial_list:
initial_list_bck[:] = initial_list[:]
# or
initial_list_bck = initial_list.copy()
# The following would create only a pointer to the first list
initial_list_bck = initial_list
Hope to be helpful.

Iterate through the list of lists. White iterating, remove the nth item.
a = [[928.7, 554.29999958311, 0],
[928.7, 558.15990063549, 0],
[914.1, 558.15990063549, 0],
[914.1, 554.29999958311, 0]]
column_number = 1
for i in range(0, len(a)):
a[i].remove(a[i][column_number])
print a

Related

Looping through list of dictionary in python

Given list of dictionary in python
my_list=[{'id':0,'name':'cube0_cluster0','member_ids': [429, 432, 435]},
{'id': 1,'name': 'cube0_cluster1','member_ids': [0, 4, 5]},
{'id':0,'name':'cube1_cluster1','member_ids': [4, 706, 800]}]
I want to print all member_ids for cube{ }_cluster1
My expected output is to print [0,4,5,706,800]
any help would be highly appreciated
I have tried it
for k in my_list:
for j in range(len(my_list)):
if k['name']=='cube{}_cluster1'.format(j):
print(k['member_ids'])
But I am getting two separate outputs as [0,4,5] and [4,706,800]
Try this one.
import re
member_ids = []
for di in my_list:
if re.match('cube\d_cluster1', di['name']):
member_ids += di['member_ids']
print(member_ids)
You can also use list comprehension.
my_list=[{'id':0,'name':'cube0_cluster0','member_ids': [429, 432, 435]},
{'id': 1,'name': 'cube0_cluster1','member_ids': [0, 4, 5]},
{'id':0,'name':'cube1_cluster1','member_ids': [4, 706, 800]}]
res = [j for i in my_list for j in i['member_ids'] if "cluster1" in i["name"]]
print (res) # return list
print (set(res)) # to return distinct data
# Result
# [0, 4, 5, 4, 706, 800]
# {0, 800, 706, 4, 5}
I hope this helps and counts!

Python - Rewrite a 2D list / numpy array in the Console

I want to rewrite/replace a 2d list or numpy array (whatever is easier) in the console:
e.g.:
[[_,_,_],
[_,_,_],
[x,_,_]]
will be replaced with
[[_,_,_],
[x,_,_],
[_,_,_]]
which will be replaced with
[[x,_,_],
[_,_,_],
[_,_,_]]
and so on...so it looks like the x is moving across the "board".
I already wrote the function that enables me to print the lists one after the other but i would rather replace them in the console output.
thanks in advance for help!
import os
import time
import numpy as np
def cls():
os.system('cls' if os.name=='nt' else 'clear')
x0 = np.array([[0, 0, 0],
[0, 0, 0],
[1, 0, 0]])
x1 = np.array([[0, 0, 0],
[2, 0, 0],
[0, 0, 0]])
x2 = np.array([[3, 0, 0],
[0, 0, 0],
[0, 0, 0]])
print(x0)
time.sleep(1)
cls()
print(x1)
time.sleep(1)
cls()
print(x2)
see How to clear the interpreter console?

Best way to shift a list in Python?

I have a list of numbers, let's say :
my_list = [2, 4, 3, 8, 1, 1]
From this list, I want to obtain a new list. This list would start with the maximum value until the end, and I want the first part (from the beginning until just before the maximum) to be added, like this :
my_new_list = [8, 1, 1, 2, 4, 3]
(basically it corresponds to a horizontal graph shift...)
Is there a simple way to do so ? :)
Apply as many as you want,
To the left:
my_list.append(my_list.pop(0))
To the right:
my_list.insert(0, my_list.pop())
How about something like this:
max_idx = my_list.index(max(my_list))
my_new_list = my_list[max_idx:] + my_list[0:max_idx]
Alternatively you can do something like the following,
def shift(l,n):
return itertools.islice(itertools.cycle(l),n,n+len(l))
my_list = [2, 4, 3, 8, 1, 1]
list(shift(my_list, 3))
Elaborating on Yasc's solution for moving the order of the list values, here's a way to shift the list to start with the maximum value:
# Find the max value:
max_value = max(my_list)
# Move the last value from the end to the beginning,
# until the max value is the first value:
while my_list[0] != max_value:
my_list.insert(0, my_list.pop())

Python 2.7 current row index on 2d array iteration

When iterating on a 2d array, how can I get the current row index? For example:
x = [[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 0. 3. 6.]]
Something like:
for rows in x:
print x current index (for example, when iterating on [ 5. 6. 7. 8.], return 1)
Enumerate is a built-in function of Python. It’s usefulness can not be summarized in a single line. Yet most of the newcomers and even some advanced programmers are unaware of it. It allows us to loop over something and have an automatic counter. Here is an example:
for counter, value in enumerate(some_list):
print(counter, value)
And there is more! enumerate also accepts an optional argument which makes it even more useful.
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value)
.
# Output:
# 1 apple
# 2 banana
# 3 grapes
# 4 pear
The optional argument allows us to tell enumerate from where to start the index. You can also create tuples containing the index and list item using a list. Here is an example:
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
.
# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]
enumerate:
In [42]: x = [[ 1, 2, 3, 4],
...: [ 5, 6, 7, 8],
...: [ 9, 0, 3, 6]]
In [43]: for index, rows in enumerate(x):
...: print('current index {}'.format(index))
...: print('current row {}'.format(rows))
...:
current index 0
current row [1, 2, 3, 4]
current index 1
current row [5, 6, 7, 8]
current index 2
current row [9, 0, 3, 6]

How to turn column of number into a list of strings?

I don't know why I cant figure this out. But I have a column of numbers that I would like to turn into a list of strings. I should of mention this when i initially posted this but this isn't a DataFrame or did it come from a file this is a result of a some code, sorry wasn't trying to waste anybody's time, I just didn't want to add a bunch of clutter. This is exactly how it prints out.
Here is my column of numbers.
3,1,3
3,1,3
3,1,3
3,3,3
3,1,1
And I would like them to look like this.
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']
I'm trying to find a way that is not dependent on how many numbers are in each row or how many sets of numbers are in the column.
Thanks, really appreciate it.
Assume you start with a DataFrame
df = pd.DataFrame([[3, 1, 3], [3, 1, 3], [3, 1, 3], [3, 3, 3], [3, 1, 1]])
df.astype(str).apply(lambda x: ','.join(x.values), axis=1).values.tolist()
Looks like:
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']
def foo():
l = []
with open("file.asd", "r") as f:
for line in f:
l.append(line)
return l
To turn your dataframe in to strings, use the astype function:
df = pd.DataFrame([[3, 1, 3], [3, 1, 3], [3, 1, 3], [3, 3, 3], [3, 1, 1]])
df = df.astype('str')
Then manipulating your columns becomes easy, you can for instance create a new column:
In [29]:
df['temp'] = df[0] + ',' + df[1] + ',' + df[2]
df
Out[29]:
0 1 2 temp
0 3 1 3 3,1,3
1 3 1 3 3,1,3
2 3 1 3 3,1,3
3 3 3 3 3,3,3
4 3 1 1 3,1,1
And then compact it into a list:
In [30]:
list(df['temp'])
Out[30]:
['3,1,3', '3,1,3', '3,1,3', '3,3,3', '3,1,1']
# Done in Jupyter notebook
# add three quotes on each side of your column.
# The advantage to dataframe is the minimal number of operations for
# reformatting your column of numbers or column of text strings into
# a single string
a = """3,1,3
3,1,3
3,1,3
3,3,3
3,1,1"""
b = f'"{a}"'
print('String created with triple quotes:')
print(b)
c = a.split('\n')
print ("Use split() function on the string. Split on newline character:")
print(c)
print ("Use splitlines() function on the string:")
print(a.splitlines())