从数据帧将列表写入文件:键

2024-09-28 03:14:21 发布

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

我被难住了-我有两个csv文件,我已经使用Pandas包上传为数据帧,然后(除其他外)我从csv文件中取出一列作为单独的列表(列“key”作为字符串列表[[keyval1,keyval2,keyval3]。你知道吗

我正在努力消除bug的是,使用日志文件.write列表长度的迭代器不断给我一个关键错误,指出:

raise KeyError('没有名为%s的项%com.pprint\u东西(项目) KeyError:u'没有名为key的项'

但它只在函数“inoutflows”中执行(在函数“sustring”中没有错误) 代码如下所示:

import pandas as pd
import csv

popkey1 = pd.read_csv("popkey1.csv", delimiter='\t')
matrix = pd.read_csv("flight1quart.csv", delimiter='\t')
listof = []
listof = popkey1['airport'].tolist()

#print popkey1
#print listof

a = 0
logfile = open("flighttest.txt", 'a')


##### CODE FOR SUSCEPTIBLE IN AND OUTFLOWS ALGORITHM ######
def susstring (l, marker):
    x = marker
    for y in range (0, len(l)):
        if x != y:
            if y != (len(l) - 1):
                logfile.write(str(l[y]) + "to" + str(l[x]) + " + ")
            else:
                logfile.write(str(l[y]) + "to" + str(l[x]) + " - ")
        else:
            a = y
    for sy in range (0, len(l)):
        if x != sy:
            logfile.write(str(l[x]) + "to" + str(l[sy]) + " - ")
        else:
            a = y
    logfile.write("siflow" + str(x + 1))

def inoutflows(li, marker2):
    numx = marker2
    logfile.write("INFLOWS:\n")
    for numy in range (0, len(li)):
        if numx != numy:
            logfile.write(str(li[numy]) + "to" + str(li[numx]) + " = City_" + str(numy+1) + "_Susceptible * " + str(matrix[li[numy]].ix[numx]) + "\n")
        else:
            a = numy
    logfile.write("OUTFLOWS:\n")
    for ny in range (0, len(li)):
        if numx != ny:
            logfile.write(str(li[numx]) + "to" + str(li[ny]) + " = City_" + str(numx+1) + "_Susceptible * " + str(matrix[li[numy]].ix[numx]) + "\n")
        else:
            a = ny
    logfile.write("siflow" + str(numx+1) + " = City_" + str(numx+1) + "_Susceptible * 0.05\n")


for x in range (0, len(listof)):
    logfile.write("City" + str(x+1) + "_Susceptible(t) = City" + str(x+1) + "_Susceptible(t - dt) + (")
#   susstring(listof, x)
    logfile.write(")) * dt\n")
    logfile.write("INIT City_" + str(x+1) + "_Susceptible = " + str(popkey1['population'].ix[x]) + "\n")
    inoutflows(listof, x)

popkey1 csv文件是一个包含三列的文件:key、airport、population flight1quart是一个矩阵,其中包含不同键之间的行程时间。你知道吗

任何关于我做错了什么的提示都将不胜感激——我已经浏览了stackoverflow和文档,但我不知道为什么它只适用于一个函数而不适用于另一个函数。你知道吗


Tags: 文件csvincityforlenliwrite

热门问题