1

I am trying to determine the best way to add a column to my pandas dataframe that converts total minutes (which is in int format) into HH:MM format. I am aware that the easiest way to do this is with datetime, but I can't seem to figure out the best way to convert the data from a Series to make this happen.

Here is the error message:

TypeError: unsupported type for timedelta minutes component: Series

Code (e.g. 346.0):

df['minutes_asleep_hm'] = str(timedelta(minutes=df['minutes_asleep']))[:-3]

Type:

Name: minutes_asleep, dtype: float64
wjandrea
  • 28,235
  • 9
  • 60
  • 81
cphill
  • 5,596
  • 16
  • 89
  • 182
  • 1
    for pandas series, you should use [Timedelta](https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Timedelta.html#pandas-timedelta) subclass within pandas itself, Also, for more better help it would be better if you include the sample series you are trying to use! – Gahan Jun 27 '20 at 17:30
  • Does this answer your question? [Convert integer series to timedelta in pandas](https://stackoverflow.com/questions/34519536/convert-integer-series-to-timedelta-in-pandas) – FObersteiner Jun 27 '20 at 17:47

1 Answers1

1

Series is essentially a list of values. You need to use a map function which applies a given operation to every element in the series and returns the result of this function as a series.

df['minutes_asleep_hm'] = df['minutes_asleep'].map(lambda x: str(timedelta(minutes=x))[:-3], na_action='ignore')

Notes:

  1. The variable x, though undescriptive, is pretty standard for lambdas and is used here to keep the line short. It represents the current series value that the function is operating on.
  2. A lambda isn't required. Any standard function will do, but a lambda was used as it's fairly standard and is a convienient one liner.
Jacobm001
  • 4,431
  • 4
  • 30
  • 51
  • This is great and what I was looking for, but what should be modified to the data to handle NaN or null values? I received this error `ValueError: cannot convert float NaN to integer` – cphill Jun 27 '20 at 18:19
  • @cphill: According to the docs, you can use the parameter `na_action`. I've updated my answer to include it. – Jacobm001 Jun 27 '20 at 18:22