python - 关于如何解决无限循环问题的建议(python-pandas)
问题描述
我有一个包含 384 行的数据框(在 bigining 中还有一个额外的虚拟行)。每行有 4 个我手动编写的变量。3 个基于这 4 个变量的计算字段。和 3 将每个计算变量与之前的行进行比较。每个字段可以有两个值之一(基本上是真/假)。
最终目标 - 我想以 6 个计算字段 (2^6) 的 64 种可能组合出现 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
解决方案
推荐阅读
- sql - someone guide me a code i want to write a procedure in sql oracle which take input from user and tell this input is character or not
- c# - 按名称对列表项进行分组
- firebase - Firestore 日志记录和自定义日志 - Firestore 中的自定义反应本机应用程序日志
- scala - Scala Guice 传递参数
- .net - 转换类型 F#
- powerbi - PowerBI 视觉效果如何在点击事件上调用更新
- python-3.x - 在 Networkx 中删除某些边缘的更好实现
- wso2 - 使用 WSO2 EI JMS 入站端点配置 IBM MQ
- node.js - 当 node.js 不在路径中时,Visual Studio Docker 失败
- mysql - 有没有办法插入一个mysql rec并自动删除具有相同密钥的旧rec