Pandas - Applying a custom function to extract year from dates in DataFrame
Pandas: Custom Function Exercise-13 with Solution
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics