Here is an example dataframe.
import pandas as pd
index_labels = pd.date_range(start='1/1/2018', end='1/08/2018')
column_labels = pd.MultiIndex.from_product([['Function A', 'Function B'],
['Fund 1', 'Fund 1', 'Fund 3']])
df = pd.DataFrame(index=index_labels, columns=column_labels)
for i in range(len(df.index)):
for j in range(len(df.columns)):
if df.columns[j][0] == 'Function A':
df.iloc[i, j] = i + 1 + j/10
else:
df.iloc[i, j] = i + 1 + j/100
df.head()
Function A Function B
Fund 1 Fund 1 Fund 3 Fund 1 Fund 1 Fund 3
2018-01-01 0.0 0.1 0.2 0.03 0.04 0.05
2018-01-02 1.0 1.1 1.2 1.03 1.04 1.05
2018-01-03 2.0 2.1 2.2 2.03 2.04 2.05
2018-01-04 3.0 3.1 3.2 3.03 3.04 3.05
2018-01-05 4.0 4.1 4.2 4.03 4.04 4.05
I would like a function to recursively append rows and modify the column level 1 name to include then number of shifts. for example fund id:number_shifts
For example, calling with 2 shifts df2 = column_shift(df, 2) should produce the following The function should also work with negative shifts
Function A Function B Function A Function B Function A Function B
Fund 1 Fund 2 Fund 3 Fund 1 Fund 2 Fund 3 Fund 1:1 Fund 2:1 Fund 3:1 Fund 1:1 Fund 2:1 Fund 3:1 Fund 1:2 Fund 2:2 Fund 3:2 Fund 1:2 Fund 2:2 Fund 3:2
2018-01-01 0.0 0.1 0.2 0.03 0.04 0.05 1.0 1.1 1.2 1.03 1.04 1.05 2.0 2.1 2.2 2.03 2.04 2.05
2018-01-02 1.0 1.1 1.2 1.03 1.04 1.05 2.0 2.1 2.2 2.03 2.04 2.05 3.0 3.1 3.2 3.03 3.04 3.05
2018-01-03 2.0 2.1 2.2 2.03 2.04 2.05 3.0 3.1 3.2 3.03 3.04 3.05 4.0 4.1 4.2 4.03 4.04 4.05
This code may not be pretty, but it works... I attempted drop, join / merge / concat, but wasn't sucessful...