Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shift multiple columns? Pandas, Python

Tags:

python

pandas

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
like image 870
Reese Fitzmaurice Avatar asked Nov 25 '17 21:11

Reese Fitzmaurice


People also ask

How do I move multiple columns in pandas?

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.

How do you shift multiple columns?

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.

How do I select multiple or more columns in pandas?

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.


1 Answers

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
like image 118
Scott Boston Avatar answered Nov 02 '22 04:11

Scott Boston