Okay, direct assignment works, but what if I want to place the new column at a specific position in my DataFrame?
You can use insert()
to control where it appears:
df.insert(4, 'e', [-0.335485, -1.166658, -0.385571])
Why this?
- The second argument (
4
) specifies that column'e'
will be added as the fifth column indf
. - Unlike direct assignment, this method lets you decide the exact position while using
pandas add column to dataframe
.
But wait, what if you want to keep the original DataFrame unchanged while adding the new column? Keep reading.