如何在csv文件中找到行之间的最小欧几里德距离并丢弃其中一行,直到我有特定的行数为止?

2024-05-02 20:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv,有570795行,代表54个主题的特征。每个主题有不同的行数,即245014857等。现在我想为一个主题创建150行,并将其存储到单独的csv中。我的代码如下所示

df=pd.read_csv("input csv")
print("input starting row")
s = int(input())
print("enter ending row")
e = int(input())
t_rows = s-e
t_rows = abs(t_rows)+1
if t_rows>150:
    print("Rows are more than 150")
    while t_rows>150:
        store = list()
        min = 100
        for x in range(s,e):
            df1 = df.iloc[x]  #row start number used as index x
            df2 = df.iloc[x+1]  #plus 1 to access next index
            df3 = np.linalg.norm(df2-df1)  #euclidean distance
            if df3<min:
                min = df3
                store.extend([x,x+1,min])  # add new items in list if min = df3
        print(min)
        print(store)
        df = df.drop(store[-2])  #delete second last item of list store i.e. index number of row having least euclidean distance
        t_rows-=1
        if t_rows == 150:
            break
        e-=1
    df=df[s:e]
    df.to_csv(str(i)+".csv", index = False, header = None)
    i+=1

这段代码运行良好。但问题是,当它删除一个具有最小距离的行并在下一次迭代搜索具有最小距离的行时,它找不到已经删除的行的索引,任何人都可以帮助我,如何在下一次迭代中跳过已经删除的行?提前谢谢