python - 当 str_ 无法提升 datetime64 时,使用 numpy.where

标签 python pandas numpy datetime

import pandas as pd
from datetime import timedelta
import numpy as np

df = pd.DataFrame({
    'open_local_data':['2022-08-24 15:00:00','2022-08-24 18:00:00'],
    'result':['WINNER','']
})
df['open_local_data'] = pd.to_datetime(df['open_local_data'])
df['clock_now'] = np.where(
    df['result'] != '',
    df['open_local_data'] + timedelta(minutes=150),
    ''
)
print(df[['open_local_data','clock_now']])

由于我必须使用条件进行工作,并且只有在稍后才决定是否处理列中的更改,因此如果收到此错误,我应该怎么做:

    df['clock_now'] = np.where(
  File "<__array_function__ internals>", line 180, in where
TypeError: The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[str_]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[str_]'>)

最佳答案

你可以.astype(str)添加,这样NumPy就会很高兴,但最后你会得到字符串。相反,您可以使用df.where:

df["clock_now"] = df["result"].where(df["result"].eq(""),
                                     other=df["open_local_data"].add(pd.Timedelta("150min")))
  • 保持“结果”值不变,它们等于空字符串
  • 并将 local_data + 150 分钟发送到其他地点

获取

>>> df

      open_local_data  result            clock_now
0 2022-08-24 15:00:00  WINNER  2022-08-24 17:30:00
1 2022-08-24 18:00:00

其中 df.at[0, "clock_now"] 实际上是时间戳,而不是字符串。

关于python - 当 str_ 无法提升 datetime64 时,使用 numpy.where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75061424/

相关文章:

python - 连接错误 SMTP python

python - Pandas:Groupby,循环并添加一小时迭代组内的条件

python - 查找一列中相对于其他列的最大值

python - NumPy:矩阵点积与 MATLAB 不兼容

python - 可以使用字符串列创建稀疏的 Pandas DataFrame 吗?

python - 如何通过 xlwt 获取 Excel 文件中的行数

python - Pandas 对列中大于 _each_ 值的所有行进行分组

python - ipython笔记本中的"import matplotlib.pyplot as plt"

python - 返回一个实值的、相位加扰的时间序列

python - 使用 Python 和 Tkinter 创建温度程序