【问题标题】:Use selected Pandas columns with a function to create a matrix使用带有函数的选定 Pandas 列来创建矩阵
【发布时间】: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


    【解决方案1】:

    您的代码中存在一些问题 -

    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
    

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

    【讨论】:

    • 感谢@Aritesh 的帮助。 i in range(len(cols_index)) 的问题在于它从零开始 i,而 cols_index 列表是从数据帧中选择的列,例如[10、17、23、24、26、52、56]。所以我认为我确实需要for i in cols_index,因为我需要我成为 [10, 17, 23, 24, 26, 52, 56],而不是 [0, 1, 2, 3, 4, 5, 6] 会返回当我调用交叉表时数据框的错误列。需要明确的是,cols_index 是一个整数列表。
    • 我的下一个问题是pd.crosstab 似乎不喜欢在相同的列上被调用:confusion_matrix = pd.crosstab(df[df.columns[i]], df[df.columns[j]] 在 i == j 时抛出错误
    • @LucieCBurgess,然后我将添加一个条件语句 if(i !=j)。此外,如果您的函数是可交换的(即您的结果不会按操作数的顺序改变,那么只运行它 j>i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2020-02-14
    • 1970-01-01
    • 2020-07-17
    • 2019-11-09
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多