-2

I read that the apply function takes the entire series as the input and apply the custom function to that series. However I applied the below function to a col in a dataframe and it worked as if It was passing data element wise (because it was spliting each value in that column and I fail to understand how it could be done on a column as a whole)

def get_date(value):
    value_str = str(value)
    d = value_str.split("T")
    d1 = pd.to_datetime(d[0])
    return d1 

In this context, it would be great if someone can clearly make a distinction between apply and applymap in python.

2
  • The first part of your question talks about how to apply a function to a series. The second part asks for the difference between apply & applymap. Is there a connection between these two parts? Commented Jun 20, 2018 at 8:16
  • For second part: stackoverflow.com/questions/19798153/… Commented Jun 20, 2018 at 14:27

1 Answer 1

0
def get_date(value):
    value_str = str(value)
    d = value_str.split(" ")
    d1 = pd.to_datetime(d[0])
    return pd.Series([d1], index=['date'])

df = pd.DataFrame({'full_date': pd.date_range('2018-6-20 10:00:00.123', periods=10, freq='5H')})
df[['date']] = df['full_date'].apply(get_date)

df(Input):

                  full_date
0   2018-06-20 10:00:00.123
1   2018-06-20 15:00:00.123
2   2018-06-20 20:00:00.123
3   2018-06-21 01:00:00.123
4   2018-06-21 06:00:00.123
5   2018-06-21 11:00:00.123
6   2018-06-21 16:00:00.123
7   2018-06-21 21:00:00.123
8   2018-06-22 02:00:00.123
9   2018-06-22 07:00:00.123

df(Ouput):

                  full_date       date
0   2018-06-20 10:00:00.123 2018-06-20
1   2018-06-20 15:00:00.123 2018-06-20
2   2018-06-20 20:00:00.123 2018-06-20
3   2018-06-21 01:00:00.123 2018-06-21
4   2018-06-21 06:00:00.123 2018-06-21
5   2018-06-21 11:00:00.123 2018-06-21
6   2018-06-21 16:00:00.123 2018-06-21
7   2018-06-21 21:00:00.123 2018-06-21
8   2018-06-22 02:00:00.123 2018-06-22
9   2018-06-22 07:00:00.123 2018-06-22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.