Moving columns in Pandas DATA FRAME

I read the data from the csv file in a data frame consisting of more than 25,000 rows and 15 columns, and I need to move all the rows (including the leftmost β†’ index) one column to the right so that I get an empty index and the ability to fill it with integers. However, column names should remain in one place. So basically I need to move everything except the column names one place to the right.

enter image description here

I tried to reindex it, but got an error:

ValueError: cannot reindex from a duplicate axis 

Is there any way to do this?

+5
source share
3 answers

In pandas, you can create a column on the right, unless you are connecting between two data files. Then you can arrange as you like.

 import pandas as pd df = pd.read_csv('data.csv', header=None, names = ['A','B','C']) print(df) ABC 0 1 2 3 1 4 5 6 2 7 8 9 3 10 11 12 df['D'] = pd.np.nan # this creates an empty series # and appends to the right print(df) ABCD 0 1 2 3 NaN 1 4 5 6 NaN 2 7 8 9 NaN 3 10 11 12 NaN df = df[['D','A','B','C']] # rearrange as you like print(df) DABC 0 NaN 1 2 3 1 NaN 4 5 6 2 NaN 7 8 9 3 NaN 10 11 12 
+9
source

First I would add a new column using

 df['new'] = df.index 

than reading the column names of your data frame in a list with:

 colnames = df.columns.tolist() 

Then you can change them as you need, for example, change the order so that you get the last β€œnew” column as the first and move the rest of the position to the right:

 colnames = colnames[-1:] + colnames[:-1] 

and reassign:

 df = df[colnames] 
+4
source
 df = YourDataFrame col = "Your Column You Want To Move To The Start Of YourDataFrame" df = pd.concat([df[col],df.drop(col,axis=1)], axis=1) 
0
source

Source: https://habr.com/ru/post/1234027/


All Articles