I have dataframe with 30 columns and want to add one new column to start.
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, ...])
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.
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
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