Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert timedelta to integer in pandas?

I have a column ‘Time’ in pandas that includes both integer and time deltas in days:

index               Time
1                     91
2                     28
3      509 days 00:00:00
4      341 days 00:00:00
5      250 days 00:00:00

I am wanting to change all of the Time deltas to integers, but I am getting many errors when trying to pick and choose which values to convert, as it throws errors when I try to convert an integer within the column rather than a TD.

I want this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index               Time
1                     91
2                     28
3                    509 
4                    341 
5                    250 

I’ve tried a few variations of this to check if it’s an integer, as I’m not concerned with those:

for x in finished['Time Future']:
    if isinstance(x, int):
        continue
    else:
        finished['Time'][x] = finished['Time'][x].astype(int)

But It is not working at all. I can’t seem to find a solution.

>Solution :

This seems to work:

# If the day counts are actual integers:
m = ~df.Time.apply(lambda x: isinstance(x, int))

# OR, in case the day counts are strings:
m = ~df.Time.str.isdigit()

df.loc[m, 'Time'] = df.Time[m].apply(lambda x: pd.Timedelta(x).days)

Results in:

  Time
1   91
2   28
3  509
4  341
5  250
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading