将选定列与函数一起使用以创建矩阵

2024-04-25 21:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数结果的矩阵,它涉及到数据帧列的交叉表。该函数依次对一对数据帧列进行操作,以便最终结果是应用于每对数据帧列的结果矩阵。我要操作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

但在这种情况下,我看不到如何使用熊猫栏目广播。你知道吗

有什么好主意,谢谢。你知道吗


Tags: columnsof数据函数indfgetindex
1条回答
网友
1楼 · 发布于 2024-04-25 21:11:11

代码中的一些问题-

  1. ij应该是数字,因为您将其用作索引。你知道吗
  2. 您需要为crosstab提供pandas.Series,您提供的是字符串(即使i和j的值正确)

请看下面代码的变化-

def fun():
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 range(len(cols_index)):
    for j in range(i+1,len(cols_index)):
        confusion_matrix = pd.crosstab(df[df.columns[cols_index[i]]], df[df.columns[cols_index[j]]]) # df.columns.get_values()[location]
        result = my_function(confusion_matrix) # a scalar
        res_matrix[i, j] = result
return res_matrix

我已经根据OPs的注释修改了代码,col\u index是列的索引列表。另外,我假设my_function是可交换的,因此我只填充上对角线矩阵。这将节省计算时间,并且不会产生i==j问题

相关问题 更多 >