Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 与参考列表比较以转换为二进制编码_Python_Pandas_Numpy - Fatal编程技术网

Python 与参考列表比较以转换为二进制编码

Python 与参考列表比较以转换为二进制编码,python,pandas,numpy,Python,Pandas,Numpy,我有这样的参考清单 ref = ['August', 'July', 'June', 'May', 'April'] def compare(lst1, lst2): binary_list = [] #final list to return j = 0 #counter to keep check on lst2 lst2_len = len(lst2) #length for item in lst1: #main loop of ref list

我有这样的参考清单

ref = ['August', 'July', 'June', 'May', 'April']
def compare(lst1, lst2):

    binary_list = [] #final list to return
    j = 0 #counter to keep check on lst2
    lst2_len = len(lst2) #length 

    for item in lst1: #main loop of ref list
        if j < lst2_len: #check counter is less than len of other list
            if item == lst2[j]:
                binary_list.append(1)
                j = j + 1
            else:
                binary_list.append(0)
        else:      # lst2 exhausted, append 0 to remaining months
            binary_list.append(0)

    return binary_list
还有一些样品清单

list1 = ['July', 'April']
list2 = ['August']
list3 = ['August', 'June', 'April']
list4 = ['April', 'June', 'May'] # Not sorted in decreasing order, as others
我想将每个列表的元素与ref list进行比较,如果元素存在,则更改为1,否则为0

因此,当我运行一个函数时,我的预期输出是

compare(ref, list1) - [0, 1, 0, 0, 1]
compare(ref, list2) - [1, 0, 0, 0, 0]
compare(ref, list3) - [1, 0, 1, 0, 1]
对于清单4,我需要首先将其按降序排序,然后进行比较

list4 = ['June', 'May', 'April']
compare(ref, list3) - [0, 0, 1, 1, 1]
目前,我的比较函数如下所示

ref = ['August', 'July', 'June', 'May', 'April']
def compare(lst1, lst2):

    binary_list = [] #final list to return
    j = 0 #counter to keep check on lst2
    lst2_len = len(lst2) #length 

    for item in lst1: #main loop of ref list
        if j < lst2_len: #check counter is less than len of other list
            if item == lst2[j]:
                binary_list.append(1)
                j = j + 1
            else:
                binary_list.append(0)
        else:      # lst2 exhausted, append 0 to remaining months
            binary_list.append(0)

    return binary_list

由于熊猫已标记,您可以利用不需要排序的位置:

def compare(r,l):
    s=pd.Series(r)
    return s.isin(l).astype(int).tolist()



是的,这会奏效,但如果我有相同的月份,比如说过去两年,在这种情况下,每个月将是两次。但是谢谢你answer@Hardikgupta我不明白,你能不能像你在不同年份的副本上说的那样,用更多的细节来更新这个问题。现在我很困惑,因为你在编辑后发布的数据框中只有月份名称作为一个系列的列表?是的,它们目前是月份名称,但仅是最后12个。问题是,如果我把这个列表扩展到最后24个,我们每个月会有两次(每年一次)。它可能发生在1年的8月,但不是去年的8月,在这种情况下,该解决方案将失败现在该解决方案肯定解决了我的问题,但我想知道如果我必须采取2年的数据,它可以容纳你如何避免在这里申请?那要花很多时间
[0, 1, 0, 0, 1]
[1, 0, 0, 0, 0]
[1, 0, 1, 0, 1]
[0, 0, 1, 1, 1]