I have a problem with a list comprehension inside a loop. I want to add items from one list to an other.
I'm using map class and zip inside the list comprehension.
from pandas import Series, DataFrame
import pandas
x = ['a', 'b', 'c', 'd', 'e']
y = [2, 3, 6, 7, 4]
ser = {'A': Series(x), 'B': Series(y)}
df = DataFrame(ser)
targets = df['A'].tolist()
df['A1999'] = [i + 1 for i in df['B']]
df['A2000'] = [i + 2 for i in df['B']]
df['A2001'] = [i + 3 for i in df['B']]
df['A2002'] = [i + 1.7 for i in df['B']]
df['A2003'] = [i + 1.1 for i in df['B']]
y = range(1999, 2004)
gaps = []
for t in targets:
temp = []
years = []
for ele in y:
target = 'A' + str(ele)
new = df[target][df['A'] == t].tolist()
temp.append(new)
years.append(ele)
gap = [list(map(list, zip(years, item))) for item in temp]
gaps.append(gap)
And the output:
[[[[1999, 3]], [[1999, 4]], [[1999, 5]], [[1999, 3.7000000000000002]],
[[1999, 3.1000000000000001]]]...
What I'm looking for is:
[[[[1999, 3]], [[2000, 4]], [[2001, 5]], [[2002, 3.7000000000000002]],
[[2003, 3.1000000000000001]]]...
How can I fix the list comprehension in order to add all years from years list and not only the first (i.e. 1999)
I tried with this example, but I think I'm doing the same thing:
gap = [[[years[i], x] for i, x in enumerate(y)] for y in temp]
or
gap = [list(map(list, zip([[y] for y in years], item))) for item in temp]
Replace gap = with this
[list((x,y[0])) for x,y in zip(years,temp)]
Related
How to simplify and automate the following syntax so that i can achieve:
Assumptions:
lenght of x and y will alway be the same
the number of value in x and y will change
Objective:
print the value in y according to the corresponding number of time that show in x
Expected Output>>> ['a', 'a', 'b', 'b', 'b', 'c']
v = len(x)
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
for i in range(x[0]):
z.append(y[0])
for i in range(x[1]):
z.append(y[1])
for i in range(x[2]):
z.append(y[2])
#if there there is forth value being added in both x and y, then it should repeat the step above#
print(z)
Look at using zip() function
z = []
for amount, item in zip(x, y):
for _ in range(amount):
z.append(item)
Or, shorter
z = []
for amount, item in zip(x, y):
z.extend(item for _ in range(amount))
You can use nested loop to do this:
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
v = len(x)
for i in range(v):
for j in range(x[i]):
z.append(y[i])
print(z)
I'm just letting another possible solution that works.
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
for idx in range(len(x)):
z += list(y[idx] * x[idx])
print(z)
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
for i in range(len(x)):
z.extend([y[i]] * x[i])
print(z)
Gives output
['a', 'a', 'b', 'b', 'b', 'c']
this will work fine.
x = [2, 3, 1]
y = ['a', 'b', 'c']
z = []
for i in x:
for o in range(i):
z.append(y[x.index(i)])
print(z)
One with repeat and chain:
z = list(chain(*map(repeat, y, x)))
Try it online!
I have a list with an odd number of elements. I want to convert it into a specific size.
My code:
alist = ['a','b','c']
cols= 2
rows = int(len(alist)/cols)+1 # 2
anarray = np.array(alist.extend([np.nan]*((rows*cols)-len(months_list)))).reshape(rows,cols)
Present output:
ValueError: cannot reshape array of size 1 into shape (2,2)
Expected output:
anarray = [['a','b'],['c',nan]]
You can try:
out = np.full((rows,cols), np.nan, dtype='object')
out.ravel()[:len(alist)] = alist
Output:
array([['a', 'b'],
['c', nan]], dtype=object)
As a side note, this might be better for you:
rows = int(np.ceil(len(alist)/cols))
You can use list comprehension to achieve the result:
li = ['a','b','c']
l = len(li)
new_list = [li[x:x+2] for x in range(l // 2)]
if l % 2 != 0:
new_list.append([li[-1], None])
print(new_list) # [['a', 'b'], ['c', None]]
Try (without any external library)
import math
alist = ['a', 'b', 'c']
cols = 2
new_list = []
steps = math.ceil(len(alist) / cols)
start = 0
for x in range(0, steps):
new_list.append(alist[x * cols: (x + 1) * cols])
new_list[-1].extend([None for t in range(cols - len(new_list[-1]))])
print(new_list)
output
[['a', 'b'], ['c', None]]
I have a list like
l = [[Alex,Jan,Fri],[John,Feb,Mon],[Alex,Jan,Fri],[Alex,Feb,Mon],[John,Jan,Mon]]
i want to filter out the list for a particular month say "Jan" and the list should look like this
l=[[Alex,2],[John,1]]
where 2 and 1 are their number of appearances in the list with a particular month using pandas
this is what i tried
import pandas as pd
li = pd.DataFrame(l, columns=['name', 'month', 'day'])
l = li.filter('month'=Jan).name.count().reset_index().values.tolist()
Use for python solution with Counter in list comprehension:
from collections import Counter
L = [list(x) for x in Counter([a for a,b,c in l if b == 'Jan']).items()]
print (L)
[['Alex', 2], ['John', 1]]
Pandas solution with DataFrame.query and Series.value_counts:
l = li.query("month=='Jan'").name.value_counts().reset_index().values.tolist()
print (l)
[['Alex', 2], ['John', 1]]
It could be done with list comprehensions and dicts
l = [['Alex','Jan','Fri'],['John','Feb','Mon'],['Alex','Jan','Fri'],['Alex','Feb','Mon'],['John','Jan','Mon']]
target_month = 'Jan'
result_dict = {}
for obs in l:
if obs[1] == target_month:
if obs[0] in result_dict.keys():
result_dict[obs[0]] += 1
else:
result_dict[obs[0]] = 1
ret_list = []
for k,v in result_dict.items():
ret_list.append([k,v])
print(ret_list)
this will output :
[['Alex', 2], ['John', 1]]
I have a array
arr = [['a', 'b', 'a'], [1, 2, 3]
I need this to be spliited based on the first array values i.e based on 'a' or 'b'. So Expected output is
arr_out_a = [1, 3]
arr_out_b = [2]
How do I do it?
Please help me correct the question,if the way I'm using words like list and array might create confusion
Use collections.defaultdict():
In [82]: arr = [['a', 'b', 'a'], [1, 2, 3]]
In [83]: from collections import defaultdict
In [84]: d = defaultdict(list)
In [85]: for i, j in zip(*arr):
....: d[i].append(j)
....:
In [86]: d
Out[86]: defaultdict(<class 'list'>, {'b': [2], 'a': [1, 3]})
Basically just append them conditionally to predefined empty lists:
arr_out_a = []
arr_out_b = []
for char, num in zip(*arr):
if char == 'a':
arr_out_a.append(num)
else:
arr_out_b.append(num)
or if you don't like the zip:
arr_out_a = []
arr_out_b = []
for idx in range(len(arr[0])):
if arr[0][idx] == 'a':
arr_out_a.append(arr[1][idx])
else:
arr_out_b.append(arr[1][idx])
Write a function called interleave that accepts three lists as arguments and returns one list which is a composite of all three lists. Note that the composite list should be ordered as in the following example:
If the three lists were
x = ['a', 'b']
y = [1, 2]
z = ['orange', 'apple']
then the composite list should be
['a', 1, 'orange', 'b', 2, 'apple'].
You may assume that all the input lists will be of the same length.
I am able to add the the lists; however , I am not able to sort the composite list into the way the assignment asks. The following is what i have so far:
x = [ 'a', 'b']
y = [1, 2]
z = [ 'orange', 'apple']
composite = []
for element in x, y, z:
composite.append(element)
print composite
You could use list_comprehension.
>>> x = ['a', 'b']
>>> y = [1, 2]
>>> z = ['orange', 'apple']
>>> [j for i in zip(x,y,z) for j in i]
['a', 1, 'orange', 'b', 2, 'apple']
To make it as a function.
def fun(x,y,z):
return [j for i in zip(x,y,z) for j in i]
x = ['a', 'b']
y = [1, 2]
z = ['orange', 'apple']
print fun(x,y,z)