我可以获取数据框三列的斜率并使用 python 中的值创建一个新列吗?

Can I get slope of three columns of a dataframe and create a new column with the values in python?

有谁知道如何在给定每一行的固定 x 轴的情况下计算三列(y 轴)的斜率? 例如,这是我的数据框:

data = {'a':  [1, 2, 3],
        'b': [3, 4, 5],
        'c': [7, 8, 9]}
df = pd.DataFrame(data, columns=['a', 'b', 'c'])

我需要创建第四列 'd',其斜率为 1、3 和 7,例如 x 轴为 1、2 和 3。这个 1, 2、3 x轴,每一行数据都要考虑。

试试这个,你可以使用 np.polyfit() 求斜率(通过将多项式的次数定义为 1)然后计算 d 并将其放入你的字典中,最后将其转换为pandas DataFrame:

import numpy as np
import pandas as pd

def compute_slope(arr):
    return round(np.polyfit([1, 2, 3], arr, 1)[0], 2)

data = {'a':  [1, 2, 3],
        'b': [3, 4, 5],
        'c': [7, 8, 9]}

data['d'] = [compute_slope(list(arr)) for arr in zip(data['a'], data['b'], data['c'])]
df = pd.DataFrame(data, columns=['a', 'b', 'c', 'd'])

compute_slope 函数中的变量 [1,2,3] 是硬编码的,因为您提到您想要这样的 x 值。

输出:

   a  b  c    d
0  1  3  7  3.0
1  2  4  8  3.0
2  3  5  9  3.0