[Tutor] Named function in a single line
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Sep 11 04:26:54 EDT 2020
On 11/09/2020 04:47, Manprit Singh wrote:
> pd.read_csv("traffic.csv",
> parse_dates = ["Date"],
> date_parser = lambda x :dt.strptime(x,'%d/%m/%Y'))
> First of all i need to know, if i am correct upto this point ? I mean to
> say my understanding of usiing parse_dates & date_parser in pd.read_csv( )
I never use pandas so can't answer tat, but it certainly
looks feasible.
> Now coming to the question if i rewrite the above code as below :
> def dt_fmt(x): return dt.strptime(x,'%d/%m/%Y')
>
> traffic = pd.read_csv("traffic.csv",i
> parse_dates=["Date"],
> date_parser=dt_fmt)
> First point is I feel this way is more clear and clean as compared to
> using the lambda function .
That's fine, many people who are not comfortable with lambdas do
the same in similar scenarios(eg callbacks in GUI code).
The only disadvantage is that if there are many such functions you
generate a lot of names to remember and your reader has to go back
and find the definition whereas the lambda exposes the expression.
But there are pros and cons to that too.
> Second point is , if I have more than one CSV file to import with all of
> them having the date column written in the same way , this dt_fmt function
> can be used for every dataframe.
Yes, and that's a strong reason for using this style in that case,
since it ensures consistency and ease of modification of the format.
You don't need to change every call to read_csv() you just change
the callback definition.
> Third point is that the dt_fmt function is defined in a single line . Is
> it acceptable to write it in this way in a professional code ?
Yes, as has already been pointed out in earlier posts it is
quite a common idiom for single line functions.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list