Pandas Series.filter.values返回与numpy数组不同的类型

时间:2014-08-12 22:16:48

标签: python numpy pandas scipy

我正在尝试在两个数组上运行scipy.stats.entropy函数。它通过apply函数在Pandas DataFrame的每一行上运行:

def calculate_H(row):
    pk = np.histogram(row.filter(regex='stuff'), bins=16)[0]
    qk = row.filter(regex='other').values
    stats.entropy(pk, qk, base=2)

df['DKL'] = df.apply(calculate_H, axis=1)

我收到以下错误:

TypeError: ufunc 'xlogy' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

(我也试过qk = row[row.filter(regex='other').index].values

我知道问题出在qk,我可以将另一个数组作为qk传递并且它可以正常工作。问题是Pandas给了我一些东西,说它是一个numpy数组,但它不是一个numpy数组。以下示例均有效:

qk1 = np.array([12024, 9643, 7681, 8193, 8012, 7846, 7615, 7484, 5966, 11484, 13627, 17749, 9820, 5336,4611, 3366])
qk2 = Series([12024, 9643, 7681, 8193, 8012, 7846, 7615, 7484, 5966, 11484, 13627, 17749, 9820, 5336,4611, 3366]).values
qk3 = df.filter(regex='other').iloc[0].values

如果我检查类型,例如type(qk) == type(qk1)它给了我真(所有numpy.ndarray)。或者,如果我使用np.array_equals,也使用True。

我所拥有的唯一提示是当我打印出工作与不工作的数组(不在底部工作)时会发生什么:

[12024  9643  7681  8193  8012  7846  7615  7484  5966 11484 13627 17749  9820  5336  4611  3366]
[12024 9643 7681 8193 8012 7846 7615 7484 5966 11484 13627 17749 9820 5336 4611 3366]

请注意,顶部的那个值之间的间距较大。

TLDR ;这两个表达式返回不同的

df.filter(regex='other').iloc[0].values
df.iloc[0].filter(regex='other').values

1 个答案:

答案 0 :(得分:2)

我怀疑qkobject数组,而不是整数数组。在calculate_H中,试试这个:

qk = row.filter(regex='other').values.astype(int)

(即将值转换为整数数组)。