python - 如何同时使用字典和数组的 for 循环

标签 python pandas numpy

我想用一些动态输入创建一个线性方程

y = θ0*x0 + θ1*x1

y = θ0*x0 + θ1*x1 + θ2*x2 + θ3*x3 + θ4*x4

为此我有 x0,x1,x2......xn 的字典 和 θ0,θ1,θ2......θn 的数组

我是Python新手,所以我尝试了这个函数,但我卡住了

所以我的问题是如何编写一个函数来获取 x_values 和 theta_values 作为参数并给出 y_values 作为输出

X = pd.DataFrame({'x0': np.ones(6), 'x1': np.linspace(0, 5, 6)})
θ = np.matrix('0 1')
def line_func(features, parameters):
    result = []
    for feat, param in zip(features.iteritems(), parameters):
        for i in feat:
            result.append(i*param)
    return result
line_func(X,θ)

最佳答案

如果您想将 theta 与一系列特征相乘,那么从技术上讲,您可以将矩阵(特征)与向量(theta)相乘。

您可以按如下方式执行此操作:

import numpy as np

x_array= x.values
theta= np.array([theta_0, theta_1])
x_array.dot(theta)

只需按照 x 中列的排序方式对 theta 向量进行排序即可。但请注意,这给出了所有 is 的 theta_i*x_i 的乘积的行总和。如果不想rowise求和,只需要写x_array * theta即可。

如果您还想使用 pandas(我不推荐)进行乘法运算,并希望获得包含列值和相应 theta 的乘积的数据框,您可以按如下方式执行此操作:

# define the theta-x mapping (theta-value per column name in x)
thetas={'x1': 1, 'x2': 3}

# create an empty result dataframe with the index of x
df_result= pd.DataFrame(index=x.index)

# assign the calculated columns in a loop
for col_name, col_series in x.iteritems():
    df_result[col_name]= col_series*thetas[col_name] 

df_result

这会导致:

   x1  x2
0   1   6
1  -1   3

关于python - 如何同时使用字典和数组的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57499216/

相关文章:

python - 类型错误 : can't multiply sequence by non-int of type "float

python - 排序 one2manyfield openerpview

python - 如何收集文本输入数据作为变量以在 If 语句中使用

python - 使用 Pandas 从具有不同行长度的文件导入数据

python - Pandas:解析 CSV,区分缺失值哨兵和恰好等于它的字符串

python - 连接两个一维 NumPy 数组

python - Numpy:从给定范围生成组合的有效方法

python - 如何创建一个数据框,其中日期范围作为列中的值?

python - 创建模糊重复键以使用模糊匹配对行求和 (Pandas)

python - 具有选择性条件的 Numpy 洗牌?