【问题标题】:How to create new columns based on multiple conditions in other columns using a for loop?如何使用 for 循环根据其他列中的多个条件创建新列?
【发布时间】: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)&amp;(elig[nestedExam]==True,),True,False)改成elig[exam+nestedExam+' Overlap'] = (elig[exam]==True)&amp;(elig[nestedExam]==True)

标签: python pandas list loops


【解决方案1】:

首先要更有效地检查您的组合,并且不重复计算,我可能会建议您使用内置库itertools

`import itertools

exam_list = ['A', 'B', 'C', 'D']
for exam1, exam2 in itertools.combinations(exam_list, 2):
    print(exam1 + '_' + exam2)
A_B
A_C
A_D
B_C
B_D
C_D

如果您确实需要所有可能的订单/组合,您可以将permutations 替换为combinations

要处理实际问题,您实际上需要的代码要少得多。如果您有两列 elig[exam1]elig[exam2] 都是布尔数组,那么 both 为 true 的数组是 (elig[exam1] &amp; elig[exam2])。这称为“按位”或“逻辑与”运算。

例如:

df = pd.DataFrame({'A': ['car', 'cat', 'hat']})
df['start=c'] = df['A'].str.startswith('c')
df['end=t'] = df['A'].str.endswith('t')
df['both'] = df['start=c'] & df['end=t']
     A  start=c  end=t   both
0  car     True  False  False
1  cat     True   True   True
2  hat    False   True  False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2020-06-02
    相关资源
    最近更新 更多