【发布时间】:2018-11-10 09:25:12
【问题描述】:
我正在尝试创建一个函数结果的矩阵,其中涉及数据框列的交叉表。该函数依次对一对数据框列进行操作,因此最终结果是应用于每一对的结果矩阵。我要操作pd.crosstab 的列的列索引位于列表cols_index 中。这是我的代码:
cols_index # list of dataframe column indices. All fine.
res_matrix = np.zeros([len(cols_index),len(cols_index)]) # square matrix of zeros, each dimension is the length of the number of columns
for i in cols_index:
for j in cols_index:
confusion_matrix = pd.crosstab(df.columns.get_values()[i], df.columns.get_values()[j]) # df.columns.get_values()[location]
result = my_function(confusion_matrix) # a scalar
res_matrix[i, j] = result
return res_matrix
但是我收到以下错误:ValueError: If using all scalar values, you must pass an index
my_function 没有问题,因为如果我在数据框的两列上运行 my_function,就没有问题:
confusion_matrix = pd.crosstab(df['colA'], df['colB'])
result = my_function(confusion_matrix) # returns 0.29999 which is fine
我尝试了各种方法来解决这个问题,包括查看这篇文章: How to fill a matrix in Python using iteration over rows and columns
但在这种情况下,我看不到如何在 Pandas 列上使用广播。
任何想法表示赞赏,谢谢。
【问题讨论】:
标签: python pandas numpy array-broadcasting numpy-ndarray