предложение о том, как решить проблему бесконечного цикла (python-pandas) - PullRequest
0 голосов
/ 20 марта 2019

У меня есть фрейм данных с 384 строками (и еще один фиктивный в большом).в каждой строке есть 4 переменные, которые я написал вручную.3 рассчитанных поля на основе этих 4 переменных.и 3, которые сравнивают каждую вычисленную переменную с предыдущей строкой.каждое поле может иметь 1 из двух значений (в основном True / False).

Конечная цель - я хочу расположить фрейм данных таким образом, чтобы 64 возможных сочетания из 6 рассчитанных полей (2 ^ 6),происходят 6 раз (2 ^ 6 * 6 = 384).Каждая итерация выполняет таблицу частот (сводку), и если одно из полей отличается от 6, оно разбивается и рандомизирует порядок.

Проблема в том, что существует 384! -12 * 6!возможные комбинации, и мой компьютер выполняет следующий сценарий более 4 дней без решения.

import pandas as pd
from numpy import random

# a function that calculates if a row is congruent or in-congruent
def set_cong(df):
    if df["left"] > df["right"] and df["left_size"] > df["right_size"] or df["left"] < df["right"] and df["left_size"] < df["right_size"]:
         return "Cong"
    else:
         return "InC"

# open file and calculate the basic fields
DF = pd.read_csv("generator.csv")
DF["distance"] = abs(DF.right-DF.left)
DF["CR"] = DF.left > DF.right
DF["Cong"] = DF.apply(set_cong, axis=1)
again = 1

# main loop to try and find optimal order
while again == 1:
    # make a copy of the DF to not have to load it each iteration
    df = DF.copy()
    again = 0
    df["rand"] = [[random.randint(low=1, high=100000)] for i in range(df.shape[0])]
    # as 3 of the fields are calculated based on the previous row the first one is a dummy and when sorted needs to stay first
    df.rand.loc[0] = 0
    Sorted = df.sort_values(['rand'])

    Sorted["Cong_n1"] = Sorted.Cong.eq(Sorted.Cong.shift())
    Sorted["Side_n1"] = Sorted.CR.eq(Sorted.CR.shift())
    Sorted["Dist_n1"] = Sorted.distance.eq(Sorted.distance.shift())
    # here the dummy is deleted
    Sorted = Sorted.drop(0, axis=0)
    grouped = Sorted.groupby(['distance', 'CR', 'Cong', 'Cong_n1', 'Dist_n1', "Side_n1"])

    for name, group in grouped:
        if group.shape[0] != 6:
            again = 1
            break

Sorted.to_csv("Edos.csv", sep="\t",index=False)
print ("bye")

кадр данных выглядит следующим образом:

left right size_left size_right distance cong CR distance_n1 cong_n1 side_n1

  1    6      22         44        5      T    F   dummy       dummy   dummy

  5    4      44         22        1      T    T     F           T       F

  2    3      44         22        1      F    F     T           F       F
...