我试图创建一个函数结果的矩阵,它涉及到数据帧列的交叉表。该函数依次对一对数据帧列进行操作,以便最终结果是应用于每对数据帧列的结果矩阵。我要操作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
,就没有问题:
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
但在这种情况下,我看不到如何使用熊猫栏目广播。你知道吗
有什么好主意,谢谢。你知道吗
代码中的一些问题-
i
和j
应该是数字,因为您将其用作索引。你知道吗crosstab
提供pandas.Series
,您提供的是字符串(即使i和j的值正确)请看下面代码的变化-
我已经根据OPs的注释修改了代码,col\u index是列的索引列表。另外,我假设
my_function
是可交换的,因此我只填充上对角线矩阵。这将节省计算时间,并且不会产生i==j
问题相关问题 更多 >
编程相关推荐