python - 熊猫将列乘以分钟
问题描述
我有一列 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 |
解决方案
改为乘以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
推荐阅读
- python - 预期隐藏 [0] 大小 (2, 8, 256),得到 [8, 256]
- java - Java 在 redhat 8.3 环境中未检测到智能卡读卡器
- python-3.x - 如果时间戳的差异不超过 5 分钟,如何将时间戳的差异放入多个会话中?
- c# - 如何一次打印2份C#
- haskell - VSCode 自动完成添加了我在 Haskell 中不需要/想要的额外信息
- javascript - 滚动到底部时如何更改导航栏的颜色?
- typescript - 将构造函数添加到打字稿中的模板类型
- google-sheets - 查找其他范围内的匹配行
- c# - 有谁知道如何检查一个排列是否在英语词典中
- html - Chrome 奇怪的 CSS 问题,在 Firefox 上运行良好