【问题标题】:numpy select TypeError: unhashable type: 'list - numpy requires listnumpy select TypeError: unhashable type: 'list - numpy 需要列表
【发布时间】:2020-07-12 13:43:53
【问题描述】:

我正在尝试使用数据框中一列的值来生成一个新列,如此 stackoverflow 帖子中所示:pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

当我尝试运行以下代码时:

conditions = [
    newData['month'] == 1,
    newData['month'] == 2,
    newData['month'] == 3,
    newData['month'] == 4,
    newData['month'] == 5,
    newData['month'] == 6,
    newData['month'] == 7,
    newData['month'] == 8,
    newData['month'] == 9,
    newData['month'] == 10,
    newData['month'] == 11,
    newData['month'] == 12]
output = [1,1,1,2,2,2,3,3,3,4,4,4]
newData['quarter'] = newData.select(conditions, output)

我收到错误TypeError: unhashable type: 'list'

我知道列表不可散列,但 numpy 需要两个参数的列表。

来自文档:

condlist : list of bool ndarrays 条件列表,用于确定从选择列表中的哪个数组获取输出元素。当满足多个条件时,使用 condlist 中遇到的第一个。

condlist : list of bool ndarrays 条件列表,用于确定从选择列表中的哪个数组获取输出元素。当满足多个条件时,使用 condlist 中遇到的第一个。

我不知道是什么问题

【问题讨论】:

  • 啊,我知道这将是我所缺少的基本内容。谢谢!

标签: python pandas numpy


【解决方案1】:

用途:

newData['quarter'] = (newData['month'].sub(1) // 3).add(1)

如果没有重复的月份并且它们是有序的:

newData['quarter'] =  newData['month'].mod(3).eq(1).cumsum().add(1)

你的问题是你想要np.select

import numpy as np
newData['quarter'] = np.select(conditions, output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2019-10-11
    • 2020-03-27
    • 2020-05-11
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多