I want to shift horizontally each row of my dataframe test_1
following the values in the corresponding rows from another dataframe df_x
. The value in each row of df_x
should define the amount of steps shifted to the left.
test_1 = pd.DataFrame([[1,2,3,4], [10,12,13,14], [20, 22, 23,24]])
df_x = pd.DataFrame([[1],[3],[2]])
My expected output would be:
Out[157]:
0 1 2 3
0 2 3 4 NA
1 14 NA NA NA
2 23 24 NA NA
I tried adapting from an answer to a similar question (how to shift columns in pandas DataFrame dynamically and independently?), and used this:
test_1.apply(lambda x: x.shift(periods = -df_x.loc[x,:]), axis = 1)
.
However, I keep getting the following error:
KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Int64Index([3, 4], dtype='int64'). See https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"
PS: If anyone also knows how to do this without converting from Xarray to Pandas, that would be even better.