我回到Python上,目前正在研究从excel工作表的各个点获取登录名和相关数字的代码,将这些数字相加,然后将该名称添加到具有相关值的字典中“低”,“中”或“高”。我已经能够使代码以函数形式工作,并且目前正在将其放入类中:
import pandas as pd
import xlrd
import sys
class aggregateActivity:
def __init__(self):
self.l = "path to excel file"
self.s = "name of excel worksheet"
self.activityAssociation = {}
dfs = pd.read_excel(self.l, self.s, usecols=[1,2,3])
numberOfLogins = dfs.sum(axis=1)
activity = {}
for index, row in dfs.iterrows():
activity[row[0]]=numberOfLogins[index]
for key in activity:
if activity.get(key) < 100:
activityAssociation[key] = "Low"
if activity.get(key) >= 100 and activity.get(key) < 200:
activityAssociation[key] = "Medium"
if activity.get(key) >= 200:
activityAssociation[key] = "High"
x = aggregateActivity()
x.activityAssociation
这里的问题是,当我运行代码时,jupyter输出一个空字典:
{}
我检查了字典是否确实添加了内容,将print(activityAssociation)
追加到了类的末尾,并可以确认是否确实如此。
答案 0 :(得分:2)
您忘记了self.
,这导致python创建一个新的activityAssociation
local 变量
import pandas as pd
import xlrd
import sys
class aggregateActivity:
def __init__(self):
self.l = "path to excel file"
self.s = "name of excel worksheet"
self.activityAssociation = {}
dfs = pd.read_excel(self.l, self.s, usecols=[1,2,3])
numberOfLogins = dfs.sum(axis=1)
activity = {}
for index, row in dfs.iterrows():
activity[row[0]]=numberOfLogins[index]
for key in activity:
if activity.get(key) < 100:
self.activityAssociation[key] = "Low"
if activity.get(key) >= 100 and activity.get(key) < 200:
self.activityAssociation[key] = "Medium"
if activity.get(key) >= 200:
self.activityAssociation[key] = "High"
x = aggregateActivity()
x.activityAssociation