首页 > 解决方案 > 熊猫将列乘以分钟

问题描述

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

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

但这没有用。

numpy.core._exceptions.UFuncTypeError: ufunc 'multiply' 不包含签名匹配类型的循环 (dtype('<U21'), dtype('<U21')) -> dtype('<U21')

回合 final_round_duration 战斗持续时间
1 00:03:00 00:03:00
3 00:02:00 00:12:00
5 00:05:00 00:25:00

标签: pythonpandas

解决方案


改为乘以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

推荐阅读