熊猫数据框仅存储迭代的最后一个值

时间:2019-07-15 13:53:49

标签: python pandas

在数据帧“ df”中,我试图将变量“欧几里德长度”的所有值与相应的“ fullpath”值存储在一起。我设法将对打印为程序输出,但不存储到数据帧中。数据框仅存储最后一个值对。

import math
import itertools
import sys
import random
import matplotlib.pyplot as plt
import numpy
import pandas as pd 


def distance(x1, y1, x2, y2):
    return math.sqrt((x1-x2)**2 +(y1-y2)**2)

def total_distance(fullpath):
    if len(fullpath) <= 1:
        return 0

    total = 0
    for i in range(1, len(fullpath)):
        pointA = fullpath[i-1]
        pointB = fullpath[i]
        total += distance(pointA[0], pointA[1], pointB[0], pointB[1])
        return total

n = 10
start_points= (0,1) 
end_points=(10,10)
generate_dots = 8
constraint_circle_radius = 1
pass_through_dots = 3
space = []

for x in range(constraint_circle_radius, n - constraint_circle_radius + 1):
    for y in range(constraint_circle_radius, n - constraint_circle_radius + 1):
        space.append((x,y))

for path in all_possible_path:
    fullpath = [start_points]+ list(path) + [end_points]
    euclidean_length = total_distance(fullpath)
    print("Path: {} has total length:{}".format(fullpath, euclidean_length))
    data = {'Path': [fullpath],
           'E Length': [euclidean_length]}
    #convert to dataframe
    df = pd.DataFrame(data)

df

1 个答案:

答案 0 :(得分:2)

下面是有问题的几行:

for path in all_possible_path:
    fullpath = [start_points]+ list(path) + [end_points]
    euclidean_length = total_distance(fullpath)
    print("Path: {} has total length:{}".format(fullpath, euclidean_length))
    data = {'Path': [fullpath],
           'E Length': [euclidean_length]}
    #convert to dataframe
    df = pd.DataFrame(data)

您为每次迭代创建一个新的数据框。

执行此操作:

paths = []    
for path in all_possible_path:
    fullpath = [start_points]+ list(path) + [end_points]
    euclidean_length = total_distance(fullpath)
    print("Path: {} has total length:{}".format(fullpath, euclidean_length))

    paths.append({'Path': [fullpath],
                           'E Length': [euclidean_length]})
df = pd.DataFrame(paths)