python - 使用另一个数据帧中的系数将方程应用于数据帧

标签 python pandas dataframe numpy data-wrangling

我必须有 2 个数据框:

input_df

Apples    Pears   Peaches   Grapes
12        23       0         4
10        0        0         4
12        16       12        5
6         0        0         11

coefficients_df

Fruit       n    w1      w2
Apples      2    0.4     40
Pears       1    0.1     43
Peaches     1    0.6     51
Grapes      2    0.5     11

我正在尝试将方程 y = w2*(1-exp(-w1*input_df^n)) 应用于 input_df。该方程从 coefficients_df

中获取系数

这是我尝试过的:

# First map coefficients_df to input_df
merged_df = input_df.merge(coefficients_df.pivot('Fruit'), on=['Apples','Pears','Peaches','Grapes'])

# Apply function to each row
output_df = merged_df.apply(lambda x: w2*(1-exp(-w1*x^n))

最佳答案

使用简单的索引对齐:

coeff = coefficients_df.set_index('Fruit')

y = coeff['w2']*(1-np.exp(-coeff['w1']*input_df**coeff['n']))

输出:

      Apples     Pears    Peaches     Grapes
0  40.000000  38.68887   0.000000  10.996310
1  40.000000   0.00000   0.000000  10.996310
2  40.000000  34.31845  50.961924  10.999959
3  39.999978   0.00000   0.000000  11.000000

关于python - 使用另一个数据帧中的系数将方程应用于数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75477157/

相关文章:

python - pandas 使用正则表达式匹配根据另一列的值设置一列的 bool 值

pandas - 如何获取pandas数据框中特定列的模式值的索引

python - Pandas 数据框条件列更新

python - 当将stderr重定向到/dev/null并由multiprocessing.map_async调用时,子进程check_output抛出异常

Python 和 Pandas : how to elegantly filter many dataframes?

python - 如何比较两个长度、顺序未知且具有重复值的列表中的每个项目,同时最小化写入并保留 Python 中的位置?

Python urllib2异常非数字端口: 'port/'

python - 重新计算平均值和标准平均值(Python,Pandas)

r - 子集数据框,其中日期在 R 中日期向量的 x 天内

python - 分区(如果适用)