使用SPSS Python脚本获取列值
我有一个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)
任何帮助都很感激!谢谢!
1 个回答
2
假设第一行是列的名称(或者你有其他方法来确定列的顺序),你可以用列名作为键,列号作为值,来创建一个字典。
这样你就会得到类似下面的结果:
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))