方程组求解器大熊猫

时间:2017-07-01 11:11:39

标签: python pandas numpy math scipy

我以此数据框为例:

<md-button addbuttons ng-click='clickCounter()' class='md-fab md-mini'>+</md-button>

我想知道是否有可能为N个未知数构建线性求解器N方程(在本例中找到木材,铁,塑料等的价格......)

非常感谢!

1 个答案:

答案 0 :(得分:3)

可以将帧转换为线性程序,其中帧中的每一行都是约束,每个材质都是一个变量。然后我们可以使用numpy solver来解决问题评论中提到的程序Rajan Chahan

import numpy as np
import pandas as pd

from numpy.linalg import solve

# Create a simple frame, with two materials - Wood & Iron.
df = pd.DataFrame({'Col1': ['Iron', 'Wood'], 'Col2': ['Wood', 'Wood'], 'Price': [3,2]})

# Extract the materials and map each material to a unique integer
# For example, "Iron"=0 and "Wood"=1
materials = pd.Series(np.unique(df.as_matrix()[:, :-1])).astype('category')

# Create a the coefficients matrix where each row is a constraint
# For example "Iron + Wood" translates into "1*x0 + 1*x1"
# And "Wood + Wood" translates into "0*x0 + 2*x1"
A = np.zeros((len(df), len(materials)))

# Iterate over all constrains and materials and fill the coefficients
for i in range(len(df)):
    for j in range(1, df.shape[1]):
        A[i, materials.cat.categories.get_loc(df.get_value(i, 'Col{}'.format(j)))] += 1

# Solve the program and the solution is an array.
# Each entry in the array correspond to a material price.
solution = solve(A, df['Price'])  # [ 2. 1.]

# Convert to a mapping per-material
material_prices = pd.Series(solution, index=materials.cat.categories)
# Iron    2.0
# Wood    1.0
# dtype: float64

如果材料数量与约束数量不同,您可以计算least-squares solution。将以上代码中的行solution = solve(A, df['Price'])替换为:

from numpy.linalg import solve, lstsq
solution = lstsq(A, df['Price'])[0]