我有一个SPSS Python脚本,该脚本遍历表并读取特定列的每一行值,并相应地设置参数值。当前,我正在使用getValueAt(rowIndex,colIndex)访问值。但是,与表名相反,必须引用列索引并不理想,因为表列可能会移动。有没有一种方法可以基于列名引用值?

样例代码

diagram = modeler.script.diagram()

for i in range(nrows):

    jobid = job_rowset.getValueAt(i, 0);
    city = job_rowset.getValueAt(i, 3);
    country = job_rowset.getValueAt(i, 4);

    diagram.setParameterValue ('BU', bu)
    diagram.setParameterValue ('City_Param', city)
    diagram.setParameterValue ('CountryID_Param', country)


任何帮助表示赞赏!谢谢!

最佳答案

假设第一行将包含名称,(或您有一些可用的东西指定列的顺序),则可以构造一个字典,其中以“列名称”作为键,并使用“列号”值。

这将给出如下信息:

name_key_dict = dict()
for i in range(ncols):
    name_key_dict[colnames[i]] = i # Assuming that names is the ordered list of columns
# I would add a check here that you have the required columns

param_col_list = [ # This constructs a list of parameters vs column numbers
    ('BU', name_key_dict.get('Bu_Col')),
    ('City_Param', name_key_dict.get('City')),
    ('CountryID_Param', name_key_dict.get('Country Code')),
]
for row in job_rowset: # Assuming job_rowset is an iterable with a member of getValue
    for (param, col) in param_col_list:
        diagram.setParameterValue(param, row.getValue(col))

10-06 15:48