How To Change Day Format To Total Second In Pandas Data Frame?

In this post, we will learn How to change the day format to total second in a pandas data frame which we can perform using two different ways that we will discuss here where we can use the apply function along with the time delta function to get.


Day to Seconds Conversion

Here we have give the example of two different functions which could be used for getting the seconds out of the given days first is using apply function()

apply Function

It is a function that we can use on the panda’s data frame to get the seconds from days and for the same, we have given an example of code to implement and get it done as per our choice.

import pandas as pd

# create a sample data frame
df = pd. DataFrame({' Duration': [3, 5, 7, 9]})

# convert days to total seconds
df[ 'Duration'] = df[ 'Duration'].apply( lambda x: pd.Timedelta( days=x). total_seconds())

print( df)

In this above given example, we create a sample datagram where we try to convert the days into total seconds with a Duration column that contains the number of days as integers. And then we uses the apply function to apply a lambda function to each and every to convert element in the Duration column where we stored the number of days we want to convert.

Here the lambda function which we used, converts the number of days to a time delta object using the ‘timedelta()’ function and then calculates the total seconds using the total seconds() function to get the answer in a total number of seconds as the result.

The output of the same will look as followed where we can see the number of seconds from the total days.

0  259200.0
1  432000.0
2  604800.0
3  777600.0

Here another method for the same is using the total second’s function to the object timedelta that could be created by specifying the column and the example of the same we have given below.

import pandas as pd

# create a sample data frame
df = pd. DataFrame({'Duration': [3, 5, 7, 9]})

# convert days to total seconds
df[' Duration'] = pd.to_ timedelta( df[ 'Duration'], unit='d').dt. total_ seconds()

print( df)

The above code will also produce the same result which we want and that is a total number of seconds in a given day.



To learn more about How to change the days’ format to total seconds in pandas data frame visit: days format to seconds in pandas

To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: