Reputation: 1233
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]
Upvotes: 3
Views: 154
Reputation: 403
Replace gap = with this
[list((x,y[0])) for x,y in zip(years,temp)]
Upvotes: 2