For simplicity sake, lets say I have this dataframe.
Date Open Close
2016-01-01 100 129
2016-01-02 198 193
2016-01-03 103 102
2016-01-04 102 109
I can't state all the column names because there are too many. So how can I shift all the columns except for two of them (Date & Close)? I want to shift all the columns except (Date & Close) back one row.
Date Open Close
2016-01-01 198 129
2016-01-02 103 193
2016-01-03 102 102
2016-01-04 NaN 109
Pandas Change Position of a Column (Last to the First) You can change the position of a pandas column in multiple ways, the simplest way would be to select the columns by positioning the last column in the first position. You can also use this approach to change the order of pandas columns in the desired order.
Move or copy rows and columns by using the mouse Select the row or column that you want to move or copy. Note: Make sure that you hold down CTRL or SHIFT during the drag-and-drop operation. If you release CTRL or SHIFT before you release the mouse button, you will move the rows or columns instead of copying them.
By using df[] & pandas. DataFrame. loc[] you can select multiple columns by names or labels. To select the columns by names, the syntax is df.
You could do it like this creating a mask for columns to exclude:
mask = ~(df.columns.isin(['Date','Close']))
cols_to_shift = df.columns[mask]
df[cols_to_shift] = df.loc[:,mask].shift(-1)
OR
df[cols_to_shift] = df[cols_to_shift].shift(-1)
Output:
Date Open Close
0 2016-01-01 198.0 129
1 2016-01-02 103.0 193
2 2016-01-03 102.0 102
3 2016-01-04 NaN 109
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With