Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a column at the beginning (leftmost end) of a DataFrame

I have dataframe with 30 columns and want to add one new column to start.

like image 549
Learnings Avatar asked Sep 19 '17 18:09

Learnings


People also ask

How do you add a column at the beginning of a DataFrame?

And you can use the insert() function to add a new column to a specific location in a pandas DataFrame: df. insert(position, 'col_name', [value1, value2, value3, ...])

How do you add a column to the left of a DataFrame?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


1 Answers

DataFrame.insert

df = pd.DataFrame({'A': ['x'] * 3, 'B': ['x'] * 3})
df

   A  B
0  x  x
1  x  x
2  x  x

seq = ['a', 'b', 'c']

# This works in-place.
df.insert(0, 'C', seq)
df

   C  A  B
0  a  x  x
1  b  x  x
2  c  x  x

pd.concat

df = pd.concat([pd.Series(seq, index=df.index, name='C'), df], axis=1)
df

   C  A  B
0  a  x  x
1  b  x  x
2  c  x  x

DataFrame.reindex + assign
Reindex first, then assign will remember the position of the original column.

df.reindex(['C', *df.columns], axis=1).assign(C=seq)

   C  A  B
0  a  x  x
1  b  x  x
2  c  x  x
like image 137
cs95 Avatar answered Oct 25 '22 06:10

cs95