user13861457
user13861457

Reputation:

Adding a dataframe column to a specific position

I am extracting a column from my dataframe, so i can process the features in the remaining dataframe columns and storing it inside a variable. What i would like to do is return that column back to it's position, for example:

Original dataframe:

samples = {'col1': [1, 3, 5, 6, 7, 9, 11, 12],
        'col2': [1, 0, 1, 1, 0, 1, 0, 1],
        'col3': [10, 15, 16, 17, 19, 12, 10, 31],
        }

df = pd.DataFrame(samples, columns = ['col1', 'col2', 'col3'])

Storing the first column inside df_col1

df_col1 = df.iloc[:, 0:0]
df = df.iloc[:, 1:]

What i would like to do is add the column inside df_col1 back to it's original position inside my data frame df as it was originally.

Upvotes: 1

Views: 1971

Answers (2)

Melis Yılmaz
Melis Yılmaz

Reputation: 1

DataFrame.insert(loc, column, value, allow_duplicates=False) loc is insertation index

Upvotes: 0

piterbarg
piterbarg

Reputation: 8219

assuming you know where the position was (you stored it somewhere), or happy to specify the position directly, let's say you want it in pos 0, use (after you removed it in your code)

df.insert(0,df_col1.columns[0], df_col1)

Upvotes: 1

Related Questions