一个熊猫式的方法来寻找满足某些条件的主体。

问题描述 投票:0回答:1

如果这太基本,我很抱歉,但我对python(尤其是pandas)完全是个新手。

我有一个大学生人文和数学成绩的样本数据。我想找到(a)在这两个领域至少选修过一门课程的学生 (b)没有选修过任何人文课程但至少选修过一门数学课程的学生。

下面是pd.DataFrame学生的前3行。

Med Humanities               Math
    History Sociology Ethics Calculus LA  Statistics
ID                                              
1   90      96        94     90       91  NaN
2   85      81        NaN    98       NaN 95
3   NaN     NaN       NaN    NaN      70  NaN

下面是我写的。这确实是个好办法,但我想知道是否有一种不使用for-loop和if-conditions的更pandas-y的方法。

bothHS = []
startS = []

for row, col in students.iterrows():
    if pd.notna(col[0:3]).sum()>0:
        if pd.notna(col[3:6]).sum()>0: bothHS.append(row)
    else:
        if pd.notna(col[3:6]).sum()>0: startS.append(row)

在这之后,我还想找到那些学过其他课程组合的人,例如:(i)历史和LA或(ii)社会学、微积分和统计学。为此,我添加了更多的if-conditions,这使得它更加混乱。有什么内置的pandas函数可以处理这些东西吗?

python python-3.x pandas pandas-groupby
1个回答
1
投票

你可以利用 &| 操作,以选择例如没有选修过任何人文课程但至少选修过一门数学课程的学生。

df.loc[(df[('Humanities', 'History')] == np.nan) & (df[('Humanities', 'Sociology')] == np.nan) & (df[('Humanities', 'Ethics')] == np.nan) & ((df[('Math', 'Calculus')] != np.nan) | (df[('Math', 'LA')] != np.nan) | (df[('Math', 'Statistics')] != np.nan))]
© www.soinside.com 2019 - 2024. All rights reserved.