【问题标题】:Is there a way to check for linearly dependent columns in a dataframe?有没有办法检查数据框中的线性相关列?
【发布时间】:2017-06-14 22:35:03
【问题描述】:

有没有办法检查 pandas 数据框中列的线性依赖关系?例如:

columns = ['A','B', 'C']
df = pd.DataFrame(columns=columns)
df.A = [0,2,3,4]
df.B = df.A*2
df.C = [8,3,5,4]
print(df)

   A  B  C
0  0  0  8
1  2  4  3
2  3  6  5
3  4  8  4

有没有办法表明B 列是A 的线性组合,但C 是独立列?我的最终目标是在数据集上运行泊松回归,但我不断收到LinAlgError: Singular matrix 错误,这意味着我的数据框不存在逆向,因此它包含依赖列。

我想提出一种编程方式来检查每个功能并确保没有依赖列。

【问题讨论】:

标签: python pandas dataframe linear-algebra


【解决方案1】:

如果您有SymPy,您可以通过sympy.matrix.rref 使用"reduced row echelon form"

>>> import sympy 
>>> reduced_form, inds = sympy.Matrix(df.values).rref()
>>> reduced_form
Matrix([
[1.0, 2.0,   0],
[  0,   0, 1.0],
[  0,   0,   0],
[  0,   0,   0]])

>>> inds
[0, 2]

枢轴列(存储为inds)表示线性无关的“列号”,您可以简单地“切掉”其他列:

>>> df.iloc[:, inds]
   A  C
0  0  8
1  2  3
2  3  5
3  4  4

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多