【发布时间】:2019-07-30 23:20:28
【问题描述】:
我正在尝试编写一个 for 循环,该循环使用布尔值创建新列,指示被引用的两个列是否都包含 True 值。我希望这个循环遍历现有列并进行比较,但我不知道如何让循环这样做。到目前为止,我一直在尝试使用引用不同列的列表。代码如下:
import pandas as pd
import numpy as np
elig = pd.read_excel('spreadsheet.xlsx')
elig['ELA'] = elig['SELECTED_EXAMS'].str.match('.*English Language Arts.*')
elig['LivEnv'] = elig['SELECTED_EXAMS'].str.match('.*Living Environment.*')
elig['USHist'] = elig['SELECTED_EXAMS'].str.match('.*US History.*')
elig['Geometry'] = elig['SELECTED_EXAMS'].str.match('.*Geometry.*')
elig['AlgebraI'] = elig['SELECTED_EXAMS'].str.match('.*Algebra I.*')
elig['GlobalHistory'] = elig['SELECTED_EXAMS'].str.match('.*Global History.*')
elig['Physics'] = elig['SELECTED_EXAMS'].str.match('.*Physics.*')
elig['AlgebraII'] = elig['SELECTED_EXAMS'].str.match('.*Algebra II.*')
elig['EarthScience'] = elig['SELECTED_EXAMS'].str.match('.*Earth Science.*')
elig['Chemistry'] = elig['SELECTED_EXAMS'].str.match('.*Chemistry.*')
elig['LOTE Spanish'] = elig['SELECTED_EXAMS'].str.match('.*LOTE – Spanish.*')
# CHANGE TO LOOP--enter columns for instances in which scorers overlap competencies (e.g. can score two different exams). This is helpful in the event that two exams are scored on the same day, and we need to resolve numbers of scorers.
exam_list = ['ELA','LiveEnv','USHist','Geometry','AlgebraI','GlobalHistory','Physics','AlgebraII','EarthScience','Chemistry','LOTE Spanish']
nestedExam_list = ['ELA','LiveEnv','USHist','Geometry','AlgebraI','GlobalHistory','Physics','AlgebraII','EarthScience','Chemistry','LOTE Spanish']
for exam in exam_list:
for nestedExam in nestedExam_list:
elig[exam+nestedExam+' Overlap'] = np.where((elig[exam]==True)&(elig[nestedExam]==True,),True,False)
我认为问题出在 np.where() 上,我想要在其中进行考试和 nestedExam 调用有问题的列,但它们只是调用列表项。错误信息如下:
ValueError Traceback (most recent call last)
<ipython-input-33-9347975b8865> in <module>
3 for exam in exam_list:
4 for nestedExam in nestedExam_list:
----> 5 elig[exam+nestedExam+' Overlap'] = np.where((elig[exam]==True)&(elig[nestedExam]==True,),True,False)
6
7 """
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops.py in wrapper(self, other)
1359
1360 res_values = na_op(self.values, other)
-> 1361 unfilled = self._constructor(res_values, index=self.index)
1362 return filler(unfilled).__finalize__(self)
1363
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
260 'Length of passed values is {val}, '
261 'index implies {ind}'
--> 262 .format(val=len(data), ind=len(index)))
263 except TypeError:
264 pass
ValueError: Length of passed values is 1, index implies 26834
有人可以帮我解决这个问题吗?
【问题讨论】:
-
你能把
elig[exam+nestedExam+' Overlap'] = np.where((elig[exam]==True)&(elig[nestedExam]==True,),True,False)改成elig[exam+nestedExam+' Overlap'] = (elig[exam]==True)&(elig[nestedExam]==True)