【问题标题】:numpy.where: TypeError: invalid type promotionnumpy.where:TypeError:无效的类型提升
【发布时间】:2018-01-29 06:55:32
【问题描述】:

我知道还有其他问题具有相同的错误名称,但没有一个与 np.where 语句匹配,而且我也无法在其中找到问题的答案

所以我制作了一个名为data 的熊猫DataFrame,并从中创建了一个名为datesSeries,即:

dates= pd.to_datetime(pd.to_timedelta(data.a_date, unit= 'D') + pd.datetime(1960,1,1), 
                      errors= 'coerse')

我需要清除一些日期,因为它们与data 中的指标不匹配,所以我尝试在使用numpy.where 保持索引正确的同时进行调整,
然而我得到了这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-2b83ed2b2468> in <module>()
----> 1 np.where(((dates.notnull()) & (data.a_IND == 0)), np.nan, dates)

TypeError: invalid type promotion

【问题讨论】:

  • 你能显示你的数据吗?

标签: python pandas numpy


【解决方案1】:

np.where(cond, x, y) 的文档说第二个和第三个参数 - x 和 y - 需要是 array 或 array_like。另外,我相信 x 和 y 必须具有相同的形状。

您的 x 是一个标量 (np.nan),而 y 是一个类似数组的对象 (dates)。也许这就是问题所在。

【讨论】:

  • 也许,但这是pandas 问题。 np.where 问题是滥用 pandas API 的副产品,所以这个答案对 OP 没有帮助。
【解决方案2】:

我遇到了类似的问题,并设法通过从索引中获取 date 属性来解决它,即这有效:

np.where(condition, df.x, df.index.date)

这不起作用:

np.where(condition, df.x, df.index)

当索引有dtype='datetime64[ns]'

希望有帮助!

【讨论】:

    【解决方案3】:

    如果要保留日期类型,请将np.nan 替换为np.datetime64('NaT')

    np.where(((dates.notnull()) & (data.a_IND == 0)), np.datetime64('NaT'), dates)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2021-04-11
      • 2020-05-19
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多