pandas zip 参数 #1 在循环 zip 时必须支持迭代错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47848342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:55:02  来源:igfitidea点击:

zip argument #1 must support iteration error when looping through zip

pythonpython-2.7pandas

提问by Daniel Gebrahanus

I have seen few other similiar issues reported however I wasn't able to replicate that solution in my case.

我很少看到其他类似问题的报告,但是我无法在我的案例中复制该解决方案。

My problem is bit more simpler as I have one list of numbers and one list of strings

我的问题更简单一些,因为我有一个数字列表和一个字符串列表

number = [21, 44, 31, 553, 63, 35]
access = ["denied", "Try Again", "Retry", "Accepted", "Error", "Success"]

I have zipped them and created a pair with each value that looks like this

我已经压缩了它们并创建了一对,每个值看起来像这样

testInput = zip(number, access)

output: 
[(21, 'denied'), (44, 'Try Again'), (31, 'Retry'), (553, 'Accepted'), (63, 'Error'), (35, 'Success')]

I am trying to loop through each pair and execute my function that maps them to a team name based on the value of the pairs. Here was my attempt:

我试图遍历每一对并执行我的函数,该函数根据对的值将它们映射到团队名称。这是我的尝试:

def mapping(number, access):
    team = ''
    checkNumberAndAccess = zip(number, access)
    for number, access in checkNumberAndAccess:
        if number in range(20,30):
            team = 'Revolt'
        elif (number in range(40,50)) and (access == 'Try Again'):
            team = 'Strike'
        elif (number in range(60,100)) and (access == 'Error'):
            team = 'Exception'
    print team
    return team

I want 'Team' variable to hold the value of the mapping output for each pair so this is where I am executing the function:

我希望“团队”变量保存每对映射输出的值,因此这是我执行函数的地方:

for number, access in testInput:
    Team = mapping(number, access)
    df = df.append({'Access Message': access, 'Number': number}, ignore_index=True)
print df

I get "TypeError: zip argument #1 must support iteration" error when executing the mapping function. Is it in the wrong place?

执行映射函数时出现“TypeError:zip 参数#1 必须支持迭代”错误。是不是放错地方了?

full code:

完整代码:

import pandas as pd

df = pd.DataFrame()


number = [21, 44, 31, 553, 63, 35]
access = ["denied", "Try Again", "Retry", "Accepted", "Error", "Success"]


def mapping(number, access):
    team = ''
    checkNumberAndAccess = zip(number, access)
    for number, access in checkNumberAndAccess:
        if number in range(20,30):
            team = 'Revolt'
        elif (number in range(40,50)) and (access == 'Try Again'):
            team = 'Strike'
        elif (number in range(60,100)) and (access == 'Error'):
            team = 'Exception'
    print team
    return team


testInput = zip(number, access)
print testInput

for number, access in testInput:
    Team = mapping(number, access)
    df = df.append({'Access Message': access, 'Number': number}, ignore_index=True)
print df

采纳答案by Saranya Sridharan

Try this .

尝试这个 。

import pandas as pd

df = pd.DataFrame()


number = [21, 44, 31, 553, 63, 35]
access = ["denied", "Try Again", "Retry", "Accepted", "Error", "Success"]


def mapping(number, access):
    team = ''

    if number in range(20,30):
        team = 'Revolt'
    elif (number in range(40,50)) and (access == 'Try Again'):
        team = 'Strike'
    elif (number in range(60,100)) and (access == 'Error'):
        team = 'Exception'
    print team
    return team


testInput = zip(number, access)
print testInput

for number, access in testInput:
    Team = mapping(number, access)
    df = df.append({'Access Message': access, 'Number': number}, ignore_index=True)
print df

Or you can pass the total list from here and zip there , process and return the final result to the calling function.Hope this helps

或者您可以从这里传递总列表并在那里压缩,处理并将最终结果返回给调用函数。希望这会有所帮助

回答by jezrael

What about pandas solution?

Pandas解决方案怎么样?

number = [21, 44, 31, 553, 63, 35]
access = ["denied", "Try Again", "Retry", "Accepted", "Error", "Success"]

#create DataFrame
df = pd.DataFrame({'number':number, 'access':access})

#create boolean masks
m1 =  df['number'].isin(range(20,30))
m2 =  df['number'].isin(range(40,50)) & (df['access'] == 'Try Again')
m3 =  df['number'].isin(range(60,100)) & (df['access'] == 'Error')

#create new column by conditions
df['Access Message'] = np.select([m1, m2,m3], ['Revolt','Strike','Exception'], default='')
print (df)
      access  number Access Message
0     denied      21         Revolt
1  Try Again      44         Strike
2      Retry      31               
3   Accepted     553               
4      Error      63      Exception
5    Success      35               


In your solution is possible in loop append output to listand last create DataFrameby constructor:

在您的解决方案中,可以在循环中将输出附加到构造函数list并最后DataFrame由构造函数创建:

number = [21, 44, 31, 553, 63, 35]
access = ["denied", "Try Again", "Retry", "Accepted", "Error", "Success"]

def mapping(number, access):
    out = []
    checkNumberAndAccess = zip(number, access)
    for number, access in checkNumberAndAccess:
        if number in range(20,30):
            out.append('Revolt')
        elif (number in range(40,50)) and (access == 'Try Again'):
            out.append('Strike')
        elif (number in range(60,100)) and (access == 'Error'):
            out.append('Exception')
        else:
            #add default value  
            out.append('')
    return out

access = mapping(number, access)

df = pd.DataFrame({'Access Message': access, 'Number': number})
print (df)
  Access Message  Number
0         Revolt      21
1         Strike      44
2                     31
3                    553
4      Exception      63
5                     35