0

If I have a pandas dataframe like this:

 2  3   4  NaN NaN  NaN
 1 NaN NaN NaN NaN  NaN
 5  6   7   2   3   NaN
 4  3  NaN NaN NaN  NaN

and an array for the number I would like to shift: array = [2, 4, 0, 3]

How do I iterate through each row to shift the columns by the number in my array to get something like this:

 NaN  NaN   2   3   4   NaN
 NaN  NaN  NaN  NaN 1   NaN
  5    6    7   2   3   NaN
 NaN  NaN  NaN  3   4   NaN

I was trying to do something like this but had no luck.

 df = pd.DataFrame(values)
 for rows in df.iterrows():
   df[rows] = df.shift[change_in_bins[rows]]
1
  • Is the last column always NaN? Commented Nov 12, 2018 at 4:48

1 Answer 1

3

Use for loop with loc and shift:

for index,value in enumerate([2, 4, 0, 3]):
    df.loc[index,:] = df.loc[index,:].shift(value)

print(df)
     0    1    2    3    4   5
0  NaN  NaN  2.0  3.0  4.0 NaN
1  NaN  NaN  NaN  NaN  1.0 NaN
2  5.0  6.0  7.0  2.0  3.0 NaN
3  NaN  NaN  NaN  4.0  3.0 NaN
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!
@TroyZaremba You are Welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.