w3resource

Pandas - Applying a custom function to extract year from dates in DataFrame


13. Transform Dates with apply()

Write a Pandas program that applies a function to transform dates in a DataFrame.

This exercise will show how to apply a custom function to transform date values in a DataFrame.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with date strings
df = pd.DataFrame({
    'Date': ['2023-01-01', '2023-06-15', '2023-12-31']
})

# Convert the 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])

# Define a custom function to extract the year
def get_year(date):
    return date.year

# Apply the function to extract the year from each date
df['Year'] = df['Date'].apply(get_year)

# Output the result
print(df)

Output:

        Date  Year
0 2023-01-01  2023
1 2023-06-15  2023
2 2023-12-31  2023                                    

Explanation:

  • Created a DataFrame with a 'Date' column containing string dates.
  • Converted the 'Date' column to a datetime format using pd.to_datetime().
  • Defined a function get_year() to extract the year from a date.
  • Applied this function to extract the year from each date in the 'Date' column.
  • Added the extracted year as a new column 'Year' in the DataFrame.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to apply a custom function to convert date strings to datetime objects in a DataFrame column using apply().
  • Write a Pandas program to use apply() to extract the month and day from a date column and create separate columns.
  • Write a Pandas program to transform a DataFrame’s date column into a different format using a custom function with apply().
  • Write a Pandas program to apply a function to a date column to compute the day of the week and add it as a new column.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.