熊猫-如何将变量作为列传递给嵌套循环?

时间:2019-01-05 19:50:00

标签: python pandas loops dataframe

我有一个嵌套循环,我试图将列表中的值传递到其中,但是它无法识别列表值。如果我将value[col]替换为value['OpNo']之类的任何列表值,它将起作用。列表值或赋值代码周围是否有特定的包装器或我需要的东西?

我尝试了像col_list = ["'OpNo'", "'StationNo'", "'Spindle'", "'OpDescription'"]这样的列表,并像col这样包装了value[[col]]标注

下面的代码收到以下异常:KeyError: 'OpNo'

row_indexer = 0
col_indexer = 1
iloc_indexer = 0
count_row = operationData.shape[0]
col_list = ['OpNo', 'StationNo', 'Spindle', 'OpDescription']
while row_indexer < count_row:    
    value = operationData.iloc[[row_indexer],[iloc_indexer]]
    for col in col_list:
        value = value[col].values[0]
        wb['OneOpSheet'].cell(row = (row_indexer + 12), column = (col_indexer + 1)).value = value
        col_indexer = (col_indexer + 1)
    row_indexer = (row_indexer + 1)
    iloc_indexer = (iloc_indexer + 1)

3 个答案:

答案 0 :(得分:2)

我不确定这是否会为您提供确切的帮助,但是也许它将为您提供正确的方向。您可以使用Pandas.DataFrame.itertuples()在数据框中的所有行上运行,并根据需要选择值。

我走得更远,并创建了一个快速的列标签字典来帮助同步嵌套循环。

我试图在必要的地方发表评论,但是如果您听不懂,请告诉我!

import pandas as pd
import openpyxl
wb = load_workbook(filename='./generic_workbook_name.xlsx')

# Created smoe data for a dataframe.
fake_data_dict = {
    'OpNo':['1','2','3','4',],
    'StationNo':['11','22','33','44',],
    'Spindle':['S1','S2','S3','S4',],
    'OpDescription':['This','is','a','description',]
    }

# Create the dataframe.
data = pd.DataFrame(fake_data_dict)

我们的数据框:

  OpNo StationNo Spindle OpDescription
0    1        11      S1          This
1    2        22      S2            is
2    3        33      S3             a
3    4        44      S4   description

脚本的其余部分:

col_list = ['OpNo','StationNo','Spindle','OpDescription']


# Create a column label dictionary; Add 1 to index for Excel cells
col_dict = {i+1:v for i, v in enumerate(col_list)}

# Iterate over each row
for idx, row in enumerate(data.itertuples(), start = 1):
    # For each key in our column dictionary [0, 1, 2, 3]
    for key in col_dict.keys():
        print('Row: {a}\n\tColumn: {b}\n\t\tValue: {c}'.format(a = idx, b = key,
                                                               # Reduce the index by 1; Get column name based on key value.
                                                               c = data.loc[idx - 1, col_dict[key]]))

输出:

Row: 1
    Column: 1
        Value: 1
Row: 1
    Column: 2
        Value: 11
Row: 1
    Column: 3
        Value: S1
Row: 1
    Column: 4
        Value: This
Row: 2
    Column: 1
        Value: 2
Row: 2
    Column: 2
        Value: 22
Row: 2
    Column: 3
        Value: S2
Row: 2
    Column: 4
        Value: is
Row: 3
    Column: 1
        Value: 3
Row: 3
    Column: 2
        Value: 33
Row: 3
    Column: 3
        Value: S3
Row: 3
    Column: 4
        Value: a
Row: 4
    Column: 1
        Value: 4
Row: 4
    Column: 2
        Value: 44
Row: 4
    Column: 3
        Value: S4
Row: 4
    Column: 4
        Value: description

请记住,这可以简化您的脚本:

for idx, row in enumerate(data.itertuples(), start = 1):
    for key in col_dict.keys():
        wb['OneOpSheet'].cell(row = (idx + 11), column = (key + 1)).value = data.loc[idx - 1, col_dict[key]]

答案 1 :(得分:0)

我认为void *返回一个数据帧。尝试value = operationData.iloc[[row_indexer],[iloc_indexer]]

答案 2 :(得分:0)

我需要在for循环中同时包含两个命令,并在完成后重置几个索引器。下面的嵌套循环完成了我所需要的:

while row_indexer < count_row:    
    for col in col_list:
        value = operationData.iloc[[row_indexer],[iloc_indexer]]
        value = value[col].values[0]
        wb['OneOpSheet'].cell(row = (row_indexer + 12), column = (col_indexer + 2)).value = value
        col_indexer += 1
        iloc_indexer += 1
    row_indexer += 1
    iloc_indexer = 0
    col_indexer = 0