[英]Python Minutes to HH:MM Conversion
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.我正在尝试确定将列添加到我的 pandas dataframe 的最佳方法,它将总分钟数(采用 int 格式)转换为 HH:MM 格式。 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 (eg 346.0):代码(例如 346.0):
df['minutes_asleep_hm'] = str(timedelta(minutes=df['minutes_asleep']))[:-3]
Type:类型:
Name: minutes_asleep, dtype: float64
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.
您需要使用map function 将给定操作应用于系列中的每个元素,并将此 function 的结果作为系列返回。
df['minutes_asleep_hm'] = df['minutes_asleep'].map(lambda x: str(timedelta(minutes=x))[:-3], na_action='ignore')
Notes:笔记:
x
, though undescriptive, is pretty standard for lambdas and is used here to keep the line short.x
,虽然没有描述性,但对于 lambdas 来说是相当标准的,在这里用于保持行短。 It represents the current series value that the function is operating on.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.