首先,我使用pandas为不同的数据聚合创建变量。然后我创建一个类,以便我可以访问这些聚合。一旦我从类创建新对象,我想将该数据发送到文本文件。我能够将该类中的一个实例发送到文本文件,但并非所有四个都附带它。我会尝试在下面写下笔记,试着解释它出错的地方。
我做错了什么?
import pandas as pd
import numpy as np
import datetime as DT
onboard = df
#get variables from data
r1 = onboard['regions'] == "Northern Region (R1)"
perm = onboard['perm_temp'] == "Perm"
temp = onboard['perm_temp'] == "Temp"
r1_perm = onboard[r1 & perm].ssno.count()
r1_temp = onboard[r1 & temp].ssno.count()
我的课程:
class Demographics(object):
'Common base class for demographics'
#Create variables for tenure
def __init__(self,perm, temp, endstrength, percent):
self.perm = perm
self.temp = temp
self.endstrength = endstrength
self.percent = percent
def displayDemo(self):
return "Perm: %s" % self.perm
return "Temp: %s" % self.temp
return "Endstrength %s" % self.endstrength
return "Percent %s" % self.percent
现在创建我的新对象:
r1_demo = Demographics(r1_perm, r1_temp, r1_total, r1_percent)
发送到.txt文件
path1 = r'C:\Users\davidlopez\Desktop\region1.txt'
target = open(path1, 'w')
target.write("\n")
target.write("region1:\n")
target.write(r1_demo.displayDemo())
target.close()
print "sent...."
所以遇到的只是第一个实例(认为这就是它的名字)和我的.txt文件看起来像这样:
Perm: 3456
但它应该看起来像:
Perm: 3456
Temp: 5677
Endstrength: 9133
Percent: 100.0
此外,我想知道是否有办法进行循环。因此,如果我有44个不同的区域,并且所有区域都是可调用的,那么如何从类中循环它们呢?
答案 0 :(得分:3)
哇!那些returns
result = "Perm: %s" \
"Temp: %s" \
"Endstrength %s " \
"Percent %s" % (self.perm, self.temp, self.endstrength, self.percent)
return result
https://docs.python.org/3.5/reference/simple_stmts.html#grammar-token-return_stmt