Python 迭代删除linregress的多个数据点

Python 迭代删除linregress的多个数据点,python,python-3.x,pandas,pandas-groupby,itertools,Python,Python 3.x,Pandas,Pandas Groupby,Itertools,数据集优先/输出优先: 我需要迭代删除多个数据点以获得斜率。注释部分说明删除哪些数据点以获得坡度 我仅用于删除一个数据点的代码如下所示: import numpy as np import pandas as pd from scipy import stats df=pd.read_excel('I:/Python/Data/trial.xlsx') grouped = df.groupby('TestEvent') df["slope"] = np.NaN for test_event

数据集优先/输出优先:

我需要迭代删除多个数据点以获得斜率。注释部分说明删除哪些数据点以获得坡度

我仅用于删除一个数据点的代码如下所示:

import numpy as np
import pandas as pd
from scipy import stats

df=pd.read_excel('I:/Python/Data/trial.xlsx')

grouped = df.groupby('TestEvent')
df["slope"] = np.NaN
for test_event, g in grouped:
    print('TestEvent: {}'.format(test_event))
    for i in g.index:
        others = g.loc[g.index != i, ["x-axis", "y-axis"]]
        slope, intercept, r_value, p_value, std_err = stats.linregress(others)
        print ("slope", slope, 'for data without pair', i)
        df.loc[i, "slope"] = slope

df.to_excel('trial4.xlsx')

使用上面的代码(n=1),我可以得到所有10个坡度,因为一次删除了一个数据点。 __ 现在我需要删除两个数据点(或n>1),保持一个常量,如图中所示,用于两个序列(111和112)

每个序列最终将给出90个斜率数据点(0,…9迭代9次)

最后,在输出数据帧中,每个序列的斜率值为90

在所有情况下,最终数据帧将具有180个斜率值(对于序列111和112)


谢谢你的阅读。非常感谢您在这方面提供的任何帮助。

使用
itertools.compositions
获得每种情况下要删除的行的列表

import numpy as np
import pandas as pd
from itertools import combinations
...
slopes = pd.DataFrame(columns=["Test Event", "Removed 1", "Removed 2", "Slope"])    
for test_event, g in grouped:
    print('TestEvent: {}'.format(test_event))
    for rows_to_drop in combinations(g.index, 2):
        others = g[["x-axis", "y-axis"]].drop(list(rows_to_drop))
        slope, intercept, r_value, p_value, std_err = stats.linregress(others)
        print ("slope", slope, 'for data without rows', rows_to_drop)
        slopes.append({"Test Event": test_event,
                    "Removed 1": rows_to_drop[0],
                    "Removed 2": rows_to_drop[1],
                    "Slope": slope}])

请注意,每个序列只有45个唯一值,而不是90个,因为删除(0,1)与删除(1,0)相同。这会将坡度存储在一个单独的新数据框中。

谢谢。它确实工作得很好。我尝试使用df.loc[I,“slope”]=slope方法将其添加到数据帧中。它似乎不起作用。excel文件没有输出。此代码在jupyter笔记本中显示数据。但是,它不会传输到excel。您共享的第一个代码我可以轻松地将其转换为excel进行进一步分析。坡度数据位于名为
slopes
的单独数据框中。如果您希望将所有数据都放在一个数据帧中,那么您需要决定希望它放在什么形状中,因为每个测试事件都有45个斜率。