Indexing a list inside a list [:][0][0] notation? - python-3.x

list1 = [[[1,2,3],[4,5,6],[7,8,9],[10,11,12]],[[13,14,15],[16,17,18],[19,20,21],[22,23,24]]]
for i in range(0,2):
print(list1[:][i][1])
output =
[4, 5, 6]
[16, 17, 18]
how do I get the above code to work such that:
desired output =
2 14
5 17
What is the correct indexing notation for the list? I'm having particular trouble with the list[:] format as it seems to be ignored by the above code. Thx

Something like?
>>> print(*map(' '.join, zip(*[map(str, list(zip(*x[:2]))[1]) for x in list1])), sep='\n')
2 14
5 17
>>>
Or:
>>> print(*map(' '.join, zip(*[(str(x[0][1]), str(x[1][1])) for x in list1])), sep='\n')
2 14
5 17
>>>
To make it work on your code you would have to do:
for i in range(0,2):
print(list1[0][i][1], list1[1][i][1])
Out:
2 14
5 17
The reason it your code didn't work is because it is getting the sublist from i, not the sublist's sublist.

Related

Problem encountered while using list as a class variable in python3.8

I am trying to learn the python class variable concepts, while doing so I have encountered below issue. I would appreciate if anyone can help me in understanding why this below mentioned behavior
Python Version 3.8
class a:
A = 6
list_a = []
def __init__(self, b , c):
self.b = b
self.c =c
def print_all(self):
print(self.b)
print(self.c)
self.list_a.append(5)
This class has b & c as instance variables, and A as class variable also list_a list as class variable
without any object instance
>>> a.A
6
>>> a.list_a
[]
with object-1
>>> ABC = a(4,3)
>>> ABC.A
6
>>> ABC.list_a
[]
>>> ABC.A = 10
>>> ABC.A
10
>>> a.A
6
>>> a.A = 20
>>> a.A
20
>>> ABC.A
10
>>> ABC.print_all()
4
3
>>> ABC.list_a
[5]
>>> a.list_a
[5]
if you observe the above code, updating A variable through ABC object is not reflecting in a.A, also applicable vice versa
but Updating List **list_a ** either through object ABC or class variable a.list_a is reflecting both in object instance and Globally
similarly with Object-2
>>> BBB = a(6,9)
>>> BBB.list_a
[5]
>>> BBB.A
6
>>> ABC.print_all()
4
3
>>> BBB.list_a
[5, 5]
>>> a.list_a
[5, 5]
>>> BBB.A = 17
>>> BBB.A
17
>>> ABC.A
10
>>> a.A
20
>>> BBB.print_all()
6
9
>>> a.list_a
[5, 5, 5]
>>> ABC.list_a
[5, 5, 5]
>>> BBB.list_a
[5, 5, 5]
Here also any changes to the list_a from any object of the class is reflecting across all the instances of class, while variable A is not
Why updating the class variable A from instances of class is not reflecting across the all other instances while update to List is flowing across other instances of class
This is probably the same issue as a list as default argument of a function: https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm

How to delete a part of a string from pandas DataFrame in Python

I have this dataframe :
df=pd.DataFrame({'a': [2, 6, 8, 9],
'date': ['2021-07-21 04:34:02',
'test_2022-17-21 04:54:22',
'test_2020-06-21 04:34:02',
'2023-12-01 11:54:52']})
df["date"].replace("test_", "")
df
I would like to delete 'test_' from the column date.
Maybe, you can help
Use str.strip(<unnecessary string>) to remove the unnecessary string:
df.date = df.date.str.strip('test_')
OUTPUT:
a date
0 2 2021-07-21 04:34:02
1 6 2022-17-21 04:54:22
2 8 2020-06-21 04:34:02
3 9 2023-12-01 11:54:52
The same question was answered here. check the link. For your specific inquiry, this one line is all you want.
df['date'] = df['date'].map(lambda x: x.lstrip('test_'))

Structural Question Regarding pandas .drop method

df2=df.drop(df[df['issue']=="prob"].index)
df2.head()
The code immediately below works fine.
But why is there a need to type df[df[ rather than the below?
df2=df.drop(df['issue']=="prob"].index)
df2.head()
I know that the immediately above won't work while the former does. I would like to understand why or know what exactly I should google.
Also ~ any advice on a more relevant title would be appreciated.
Thanks!
Option 1: df[df['issue']=="prob"] produces a DataFrame with a subset of values.
Option 2: df['issue']=="prob" produces a pandas.Series with a Boolean for every row.
.drop works for Option 1, because it knows to just drop the selected indices, vs. all of the indices returned from Option 2.
I would use the following methods to remove rows.
Use ~ (not) to select the opposite of the Boolean selection.
df = df[~(df.treatment == 'Yes')]
Select rows with only the desired value
df = df[(df.treatment == 'No')]
import pandas as pd
import numpy as np
import random
# sample dataframe
np.random.seed(365)
random.seed(365)
rows = 25
data = {'a': np.random.randint(10, size=(rows)),
'groups': [random.choice(['1-5', '6-25', '26-100', '100-500', '500-1000', '>1000']) for _ in range(rows)],
'treatment': [random.choice(['Yes', 'No']) for _ in range(rows)],
'date': pd.bdate_range(datetime.today(), freq='d', periods=rows).tolist()}
df = pd.DataFrame(data)
df[df.treatment == 'Yes'].index
Produces just the indices where treatment is 'Yes', therefore df.drop(df[df.treatment == 'Yes'].index) only drops the indices in the list.
df[df.treatment == 'Yes'].index
[out]:
Int64Index([0, 1, 2, 4, 6, 7, 8, 11, 12, 13, 14, 15, 19, 21], dtype='int64')
df.drop(df[df.treatment == 'Yes'].index)
[out]:
a groups treatment date
3 5 6-25 No 2020-08-15
5 2 500-1000 No 2020-08-17
9 0 500-1000 No 2020-08-21
10 3 100-500 No 2020-08-22
16 8 1-5 No 2020-08-28
17 4 1-5 No 2020-08-29
18 3 1-5 No 2020-08-30
20 6 500-1000 No 2020-09-01
22 6 6-25 No 2020-09-03
23 8 100-500 No 2020-09-04
24 9 26-100 No 2020-09-05
(df.treatment == 'Yes').index
Produces all of the indices, therefore df.drop((df.treatment == 'Yes').index) drops all of the indices, leaving an empty dataframe.
(df.treatment == 'Yes').index
[out]:
RangeIndex(start=0, stop=25, step=1)
df.drop((df.treatment == 'Yes').index)
[out]:
Empty DataFrame
Columns: [a, groups, treatment, date]
Index: []

How to remove a 2 digit number from a list?

I am trying to figure out how to remove all values from a list that have 2 digits. Right now I am getting an error message and do not know how it should look, here's what I have:
import random
list1=[0]*20
for c in range(0,20):
list1[c]=random.randint(0,100)
print(list1[c])
for c in range(0,20):
if (list1[c]>9):
list1.pop(c)
print (list1)
I keep getting an index out of range error, if somebody has any Idea that would be great thanks!
You get an index out of range error because as you keep popping the list in the loop, the list gets shorter and shorter, where as the index increase according to it previously assigned length.
Lets say you had:
[10 2 3 23 3]
This is roughly what is happening in your code in the loop:
index 0: Is 10 > 9 ---> true. pop(0). Updated List: [2 3 23 3]
(Notice: How all indices have changed.)
index 1: Is 3 > 9 ---> false
index 2: Is 23 > 9 ---> true. pop(2). Updated List: [2 3 3]
index 3: There is no index 3 in the updated list. Hence the error!
A simple solution to your code could be:
import random
list1=[0]*20
for c in range(0,20):
list1[c]=random.randint(0,100)
print(list1[c])
list2 = []
for c in range(0,20):
if (list1[c]<10):
list2.append(list1[c])
print (list2)
Hope it answers you question. :)
use remove instead of pop:
>>> mylist = ['one', 'two', 'three', 'four']
>>> mylist.remove('two')
>>> print mylist
['one', 'three', 'four']
Your code should be like this:
list1.remove(c)

How to pass a map to a function in Python 3?

I get a map of numbers from user and I want to pass the map to a function. I am able to display the map, but I can't find its length. I understand that in Python 3, maps have no length and they have to be converted in lists, but I had no success with that. I also noticed that if I attempt to display the length of the map before calling function info, then the info() will print an empty map.
def info(phys):
print("phys =",list(phys)) # it displays correctly only if I comment line 10
print("len =",len(list(phys))) # it always displays 0 and I expect 3
for i in phys:
print(str(i))
return
phys = map(int, input().strip().split()) # I pass "1 2 3"
print("len(phys) =",len(list(phys))) # if this command executes before next, line 2 will print "phys = []"
info(phys)
The result of a map() call is a generator which will yield resulting values only once. See relevant documentation about map.
>>> phys = map(int, input().strip().split())
1 2 3 4
>>> list(phys)
[1, 2, 3, 4]
>>> list(phys)
[] # Second attempt to iterate through "phys" does not return anything anymore
Apparently you want to materialize the values and work with them later. Then store them:
>>> phys = map(int, input().strip().split())
1 2 3 4
>>> result = list(phys)
>>> len(result)
4
>>> result[1]
2
>>> result[-2:]
[3, 4]

Resources