-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.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 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? – jpp Jun 20 '18 at 08:16
  • For second part: https://stackoverflow.com/questions/19798153/difference-between-map-applymap-and-apply-methods-in-pandas – Pygirl Jun 20 '18 at 14:27

1 Answers1

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
Pygirl
  • 12,969
  • 5
  • 30
  • 43