Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between pandas assign() function and apply() function?

I'm learning data exploration in Python. While practising the pandas library, I saw two functions named df.assign() and df.apply(). The definition of both functions looked very similar. Can you please explain to me these two functions and their unique use cases?

like image 627
Samar Pratap Singh Avatar asked May 17 '26 14:05

Samar Pratap Singh


1 Answers

The difference concerns whether you wish to modify an existing frame, or create a new frame while maintaining the original frame as it was.

In particular, DataFrame.assign returns you a new object that has a copy of the original data with the requested changes, the original frame remains unchanged.

For example:

df = DataFrame({'A': range(1, 11), 'B': np.random.randn(10)})

If you wish to create a new frame in which A is everywhere 1 without destroying df, you could use .assign

new_df = df.assign(A=1)

Although .apply is not intended to be used to modify a dataframe, there is no guarantee that applying the function will not change the dataframe.

like image 111
Edmund Avatar answered May 20 '26 04:05

Edmund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!