【问题标题】:pandas multiply column by minutes熊猫将列乘以分钟
【发布时间】:2021-07-22 09:30:14
【问题描述】:

我有一列 df['Rounds'] 是 int64,值可以是 1-5。

我需要计算战斗时长((df[Rounds]-1)*(00:05:00))+df['final_round_duration']

但这不起作用。

numpy.core._exceptions.UFuncTypeError: ufunc 'multiply' 不包含带有签名匹配类型的循环 (dtype(' dtype('

Rounds final_round_duration fight_duration
1 00:03:00 00:03:00
3 00:02:00 00:12:00
5 00:05:00 00:25:00

【问题讨论】:

  • 您能否提供一些示例数据和预期输出?
  • 随请求更新

标签: python pandas


【解决方案1】:

改为乘以pd.Timedelta

import pandas as pd

df = pd.DataFrame({'Rounds': [1, 3, 5],
                   'final_round_duration': ['00:03:00', '00:02:00', '00:05:00']})

# Calculate Duration Time
df['flight_duration'] = (df['Rounds'] - 1) * pd.Timedelta(minutes=5) + \
                        pd.to_timedelta(df['final_round_duration'])

print(df.to_string(index=False))

输出:

回合 final_round_duration flight_duration 1 00:03:00 0 天 00:03:00 3 00:02:00 0 天 00:12:00 5 00:05:00 0 天 00:25:00

时间增量可以重新格式化为小时、分钟和秒

(见。timedelta to string type in pandas dataframe

import pandas as pd


def format_timedelta(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f'{int(hours)}:{int(minutes):02d}:{ int(seconds):02d}'


df = pd.DataFrame({'Rounds': [1, 3, 5],
                   'final_round_duration': ['00:03:00', '00:02:00', '00:05:00']})

# Calculate Duration Time
df['flight_duration'] = (
        (df['Rounds'] - 1)
        * pd.Timedelta(minutes=5)
        + pd.to_timedelta(df['final_round_duration'])
).apply(format_timedelta) # Apply Formatting

print(df.to_string(index=False))

输出:

回合 final_round_duration flight_duration 1 00:03:00 0:03:00 3 00:02:00 0:12:00 5 00:05:00 0:25:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2020-04-06
    相关资源
    最近更新 更多