What Is Difference Between. Map(Str) And. Astype(Str) in Dataframe

I have a dataframe with column name col1 and col2 of integer type entries. I want to join the entries of the col1 with col2 along with a '.'(dot) in between. I have searched and found to add two column entries :

df['col'] = df['col1'].map(str) + df['col2'].map(str)

and for add a dot :

df['col'] = df['col1'].astype(str) + '.'

but I want something like this

df['col'] = each entries of df['col1'] + '.' + each entries of df['col2']

what is the difference between .map(str) and .astype(str). and which suits in my case.

1

1 Answer

map will take every single element of the original list and apply a function or lambda expression. In this compact form, your function is str(). It has more applications than that. You could for example edit every element returning a new list. This is possible because a DataFrame cell is castable to string.

astype is a Pandas function for DataFrames (and numpy for numpy arrays) that will cast the object to the specified type and therefore here it makes little practical difference except it may be more performant since it is just 1 operation compared to multiple calls and it is natively defined in Pandas. Time-it to verify. To be noted: the astype cast, as also with map, creates a new object, not mutating the existent.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest