I want to create a list of columns where the new columns are based on previous columns times 1.5
. It will roll until Year 2020. I tried to use previous and current but it didn’t work as expected. How can I make it work as expected?
JavaScript
x
11
11
1
df = pd.DataFrame({
2
'us2000':[5,3,6,9,2,4],
3
4
}); df
5
6
a = []
7
for i in range(1, 21):
8
a.append("us202" + str(i))
9
for previous, current in zip(a, a[1:]):
10
df[current] = df[previous] * 1.5
11
Advertisement
Answer
IIUC you can fix you code with:
JavaScript
1
6
1
a = []
2
for i in range(0, 21):
3
a.append(f'us20{i:02}')
4
for previous, current in zip(a, a[1:]):
5
df[current] = df[previous] * 1.5
6
Another, vectorial, approach with numpy would be:
JavaScript
1
3
1
df2 = (pd.DataFrame(df['us2000'].to_numpy()[:,None]*1.5**np.arange(21),
2
columns=[f'us20{i:02}' for i in range(21)]))
3
output:
JavaScript
1
8
1
us2000 us2001 us2002 us2003 us2004 us2005 us2006 us2007
2
0 5 7.5 11.25 16.875 25.3125 37.96875 56.953125 85.429688
3
1 3 4.5 6.75 10.125 15.1875 22.78125 34.171875 51.257812
4
2 6 9.0 13.50 20.250 30.3750 45.56250 68.343750 102.515625
5
3 9 13.5 20.25 30.375 45.5625 68.34375 102.515625 153.773438
6
4 2 3.0 4.50 6.750 10.1250 15.18750 22.781250 34.171875
7
5 4 6.0 9.00 13.500 20.2500 30.37500 45.562500 68.343750
8