Python/Pandas-如何在时间持续时间内进行计算?

发布于 2025-01-21 15:30:29 字数 306 浏览 3 评论 0原文

我的数据具有一个“ duration_time”,每行的持续时间(ex:10:58)包含分钟和秒。

我该如何计算此“ duration_time”列(ex:sum sum以获取总持续时间,平均持续时间等?)

是什么dtype是什么最适合此类型的时间计算?

我的列的dtype列出为对象,并且不允许我执行计算。

预先感谢您的帮助!

My data has a column "duration_time" with time durations for each row (ex: 10:58) containing minutes and seconds.

How can I do calculations of this "duration_time" column (for ex: sum all to get total duration time, mean duration time, etc?)

What Dtype is best suited for this type of time calculations?

The Dtype of my column is listed as an object and doesn't let me perform calculations.

Thank you in advance for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落墨 2025-01-28 15:30:29

熊猫确实有一种时间代表,旨在表示持续时间。

您将必须进行一些解析,但是Pandas中有一个to_timedelta功能可以帮助您(

def parser(t):
    mins, secs = t.split(":")
    return 60 * mins + secs


tds = pd.to_timedelta(
    df.duration_time.map(parser), 
    unit="seconds",
)

您可能会发现这更适合您想做的计算。

Pandas does have a Timedelta type that is intended to represent durations.

You will have to do some parsing, but there is a to_timedelta function in pandas that will help you (reference here).

def parser(t):
    mins, secs = t.split(":")
    return 60 * mins + secs


tds = pd.to_timedelta(
    df.duration_time.map(parser), 
    unit="seconds",
)

You may find this more suited to the kind of calculation you want to do.

夕色琉璃 2025-01-28 15:30:29

duration_time列当前是“对象” dtype,这意味着它存储为字符串。为了使其可以使用数学,您需要提取数字值。下面的代码以该格式帐户持续时间,并在秒内返回数值:

def str_to_seconds(str_val):
    str_val = str_val.strip()
    mins, secs = str_val.split(':')
    return int(mins) * 60 + float(secs)

your_dataframe['duration_seconds'] = your_dataframe['duration_time'].map(str_to_seconds)

The duration_time column is currently an 'object' dtype, meaning it's stored as strings. To make it so you can do math with it, you need to extract the numeric values. The code below accounts for durations in that format and returns the numeric value in seconds:

def str_to_seconds(str_val):
    str_val = str_val.strip()
    mins, secs = str_val.split(':')
    return int(mins) * 60 + float(secs)

your_dataframe['duration_seconds'] = your_dataframe['duration_time'].map(str_to_seconds)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文