【问题标题】:Iteratively deleting more than one datapoints for linregress Pandas迭代删除 linregress Pandas 的多个数据点
【发布时间】:2019-03-06 02:29:56
【问题描述】:

数据集优先/输出优先:

我需要反复删除多个数据点以获得斜率。评论部分说明删除了哪些数据点以获得斜率。

我只删除一个数据点的代码如下:

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)

感谢阅读。非常感谢您对此事的任何帮助。

【问题讨论】:

    标签: python python-3.x pandas pandas-groupby itertools


    【解决方案1】:

    使用itertools.combinations 获取在每种情况下要删除的行的列表。

    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 notebook 中的数据。但是,它不会转移到excel。您分享的第一个代码我可以轻松地将其转换为 excel 以进行进一步分析。
    • 坡度数据位于名为 slopes 的单独数据框中。如果您想在 1 个数据帧中全部使用,则需要确定您想要的形状,因为每个测试事件有 45 个斜率。
    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    相关资源
    最近更新 更多