2

I'd like to make whole columns data moved to left. Only data should be shifted to the left 1 time and the columns should be fixed. Could you tell me how can I do this?

Initial Data is :

              A1   A2   A3   A4   A5
     #0001    421  000  000  777  888
     #0002    382  403  430  320  055
     #0003    441  304  403  403  403
     #0004    430  403  206  N/A  312
     #0005    N/A  394  493  N/A  403

Desire Data is :

              A1   A2   A3   A4   A5
     #0001    000  000  777  888  N/A
     #0002    403  430  320  055  N/A
     #0003    304  403  403  403  N/A
     #0004    403  206  N/A  312  N/A
     #0005    394  493  N/A  403  N/A
Landon Nam
  • 99
  • 1
  • 4
  • https://stackoverflow.com/a/47898659/4909087 works for numeric data, check the link. – cs95 Nov 15 '18 at 05:32
  • @coldspeed Can you please write a comment on how to use `justify` to this scenario. To learn how it works before deleting my answer. – Space Impact Nov 15 '18 at 05:59
  • @SandeepKadapa If they are numbers, you can simply pass an array to [`justify`](https://stackoverflow.com/a/44559180/4909087): `v = df.values; v = justify(v); df.values[:] = v` – cs95 Nov 15 '18 at 06:02
  • @coldspeed Checked isn't giving right results also the output array contains extreme values `-2147483648` in place of `np.nan`. Could you verify it?. – Space Impact Nov 15 '18 at 06:10
  • @coldspeed : that question is quite different. This question can be solved by much simpler answers. – rnso Nov 15 '18 at 06:38

2 Answers2

2

Try this simple loop:

for i in range(len(df.columns)-1):  # loop till last but one column
    df.iloc[:,i] = df.iloc[:,i+1]   # each column gets values of next column

df[i+1] = np.nan                    # for last column;

Output:

        A1   A2     A3   A4  A5
#0001    0    0  777.0  888 NaN
#0002  403  430  320.0   55 NaN
#0003  304  403  403.0  403 NaN
#0004  403  206    NaN  312 NaN
#0005  394  493    NaN  403 NaN
rnso
  • 23,686
  • 25
  • 112
  • 234
1

Use double transpose with shift:

df = df.T.shift(-1,axis=0).T

print(df)

          A1     A2     A3     A4  A5
#0001    0.0    0.0  777.0  888.0 NaN
#0002  403.0  430.0  320.0   55.0 NaN
#0003  304.0  403.0  403.0  403.0 NaN
#0004  403.0  206.0    NaN  312.0 NaN
#0005  394.0  493.0    NaN  403.0 NaN

Actually df.shift(-1,axis=1) should work but there is bug in the code:

print(df.shift(-1,axis=1))
          A1     A2     A3  A4  A5
#0001  777.0    0.0  888.0 NaN NaN
#0002  320.0  430.0   55.0 NaN NaN
#0003  403.0  403.0  403.0 NaN NaN
#0004    NaN  206.0  312.0 NaN NaN
#0005    NaN  493.0  403.0 NaN NaN
Space Impact
  • 13,085
  • 23
  • 48