Horje
Change String To Date In Pandas Dataframe

Working with date and time data in data frame are common, sometimes date information is stored as strings in datasets and needs to be converted to proper date format for analysis and visualization purposes.

Change String to Date Format in Pandas DataFrame

In this article, we will explore how to convert string data to date format within a Pandas DataFrame. There are two different methods:

1. Using pandas.to_datetime()

We can convert string to date in a data frame with pandas.to_datatime()function.

Here, we create a data frame with two columns one with dates as a string and the other with random values, then we use the pandas to_datetime() function with the date column as the parameter. Finally, it converts the Date string column from a string to a DateTime object and creates a new column Date.

Python
import pandas as pd

# Example Data
data = {
    'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],
    'Values': [100, 200, 300]
}

# Creating DataFrame
df = pd.DataFrame(data)

print("Before converting")
print(df.dtypes)

# Using pandas.to_datetime()
df['Date'] = pd.to_datetime(df['Date'])

print("\nAfter converting")
print(df.dtypes)

Output:

Before converting
Date object
Values int64
dtype: object
After converting
Date datetime64[ns]
Values int64
dtype: object

As you can observe, The ‘DateStrings’ column typically has an object (string) data type, and the ‘Values’ column has an integer data type. The ‘DateStrings’ column is not affected by the conversion operation, as the conversion result is stored in a new column ‘Date’.

2. Using DataFrame.astype()

We can use the pandas astype() function to convert string to date in the data frame.

Here, we create a data frame with two columns one with dates as a string and the other with random values, then we use the pandas astype() function with the date column. Finally, it converts the Date string column from a string to a DateTime object and creates a new column Date.

Python
import pandas as pd

# Example Data
data = {
    'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],
    'Values': [100, 200, 300]
}

# Creating DataFrame
df = pd.DataFrame(data)

print("Before converting")
print(df.dtypes)

# Using DataFrame.astype()
df['Date'] = df['Date'].astype('datetime64[ns]')

print("\nAfter converting")
print(df.dtypes)

Output:

Before converting
Date object
Values int64
dtype: object
After converting
Date datetime64[ns]
Values int64
dtype: object

As you can observe, The ‘DateStrings’ column typically has an object (string) data type, and the ‘Values’ column has an integer data type. The ‘DateStrings’ column is not affected by the conversion operation, as the conversion result is stored in a new column ‘Date’.

Conclusion

In conclusion, we discussed different methods to Change String To Date In Dataframe with pandas.to_datetime() and DataFrame.astype() functions.

Change String To Date In Pandas Dataframe – FAQs

How to Convert String to Date in Pandas DataFrame

To convert a column in a Pandas DataFrame from a string to a datetime type, you can use the pd.to_datetime function. Here’s an example:

import pandas as pd

# Sample DataFrame
data = {'date_str': ['2023-07-12', '2023-07-13', '2023-07-14']}
df = pd.DataFrame(data)

# Convert string to datetime
df['date'] = pd.to_datetime(df['date_str'])

print(df)

How to Convert String to Date in Python

To convert a string to a date in Python, you can use the datetime module. Here’s an example:

from datetime import datetime

# Sample date string
date_str = '2023-07-12'

# Convert string to date
date_obj = datetime.strptime(date_str, '%Y-%m-%d')

print(date_obj)

How to Change Format to Date in Pandas

If you want to change the format of a date column in a Pandas DataFrame, you can use the dt.strftime method. Here’s an example:

import pandas as pd

# Sample DataFrame with datetime column
data = {'date': pd.to_datetime(['2023-07-12', '2023-07-13', '2023-07-14'])}
df = pd.DataFrame(data)

# Change format of date column
df['date_formatted'] = df['date'].dt.strftime('%d-%m-%Y')

print(df)

How to Convert String Index to Date in Pandas

To convert a string index to a datetime index in a Pandas DataFrame, you can use the pd.to_datetime function. Here’s an example:

import pandas as pd

# Sample DataFrame with string index
data = {'value': [10, 20, 30]}
index = ['2023-07-12', '2023-07-13', '2023-07-14']
df = pd.DataFrame(data, index=index)

# Convert string index to datetime index
df.index = pd.to_datetime(df.index)

print(df)

How to Convert Date Index to String in Pandas

To convert a datetime index to a string index in a Pandas DataFrame, you can use the dt.strftime method. Here’s an example:

import pandas as pd

# Sample DataFrame with datetime index
data = {'value': [10, 20, 30]}
index = pd.to_datetime(['2023-07-12', '2023-07-13', '2023-07-14'])
df = pd.DataFrame(data, index=index)

# Convert datetime index to string index
df.index = df.index.strftime('%Y-%m-%d')

print(df)



Reffered: https://www.geeksforgeeks.org


Pandas

Related
Convert Bytes To a Pandas Dataframe Convert Bytes To a Pandas Dataframe
How to Change Pandas Dataframe Datetime to Time How to Change Pandas Dataframe Datetime to Time
Convert A Datetime Object To Seconds Convert A Datetime Object To Seconds
Reading An Arff File To Pandas Dataframe Reading An Arff File To Pandas Dataframe
How to Use rbind in Python? How to Use rbind in Python?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11