How to apply a self defined function in Pandas
Shaozhong SHI
shishaozhong at gmail.com
Sun Oct 31 15:52:18 EDT 2021
On Sun, 31 Oct 2021 at 19:28, MRAB <python at mrabarnett.plus.com> wrote:
> On 2021-10-31 18:48, Shaozhong SHI wrote:
> >
> > On Sunday, 31 October 2021, MRAB <python at mrabarnett.plus.com> wrote:
> >
> > On 2021-10-31 17:25, Shaozhong SHI wrote:
> >
> > I defined a function and apply it to a column in Pandas. But
> > it does not
> > return correct values.
> >
> > I am trying to test which url in a column full of url to see
> > which one can
> > be connected to or not
> >
> > def connect(url):
> > try:
> > urllib.request.urlopen(url)
> > return True
> > except:
> > return False
> >
> > df['URL'] = df.apply(lambda x: connect(df['URL']), axis=1)
> >
> > I ran without any error, but did not return any true.
> >
> > I just could not find any error with it.
> >
> > Can anyone try and find out why
> >
> > You're passing a function to '.apply'. That has one argument,' x'.
> >
> > But what is the function doing with that argument?
> >
> > Nothing.
> >
> > The function is just returning the result of connect(df['URL']).
> >
> > df['URL'] is a column, so you're passing a column to '.urlopen',
> > which, of course, it doesn't understand.
> >
> > So 'connect' returns False.
> >
> >
> > Please expand on how.
> >
> It's as simple as passing 'connect' to '.apply' as the first argument.
>
Well, can you expand the the simplicity?
Regards, David
> --
> https://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list