2014-11-05 76 views
2

我有一個SPSS Python腳本,它可以遍歷表並讀取特定列的每行值並相應地設置參數值。目前,我正在使用getValueAt(rowIndex,colIndex)訪問值。但是,不得不引用列索引而不是列名稱,因爲表列可能會發生變化。有沒有辦法根據列名引用值?使用SPSS獲取列值Python腳本

示例代碼

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) 

任何幫助表示讚賞!謝謝!

回答

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)) 
+0

謝謝!這個建議在創建name_key_dict和最後的迭代中進行了一些小的調整。 – 2014-11-05 10:51:06