首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Pandas Dataframe在使用多列值进行筛选后获得行数

Python Pandas Dataframe在使用多列值进行筛选后获得行数
EN

Stack Overflow用户
提问于 2017-04-20 06:28:55
回答 1查看 10.2K关注 0票数 2

我有一个如下所示的数据。我希望通过获取以下计数来构建数据配置文件。

1) 唯一学生ID(学生人数)的计数--我的答案是:

代码语言:javascript
复制
print(len(df['Student ID'].unique()))

2)唯一学生ID的计数,其中 International=N (非国际学生人数)

我的答案行不通:print(len(df1.loc[(df1['Student ID'].unique())['International Student'] == N]))

3)计算唯一的学生ID,其中International=N和ATAR是null(有ATAR的非国际学生的数量)。

4)在 0-50之间的唯一学生ID的计数。

其他一些问题:

5)如何使用唯一的带有所有其他列的学生ID创建一个新的,在第一个列之后删除每个学生ID的所有行

如能回答问题2-5,将不胜感激。

代码语言:javascript
复制
Student_ID            International       marks      ATAR

119                   N                    60         80
119                   N                    70         80
119                   N                    75         80
129                   Y                    78         75
129                   Y                    60         75 
155                   Y                    85         
155                   Y                    80          
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-20 06:37:18

代码语言:javascript
复制
df = pd.DataFrame({
'International': ['N', 'N', 'N', 'Y', 'Y', 'Y', 'Y'], 
'marks': [60, 70, 75, 78, 60, 85, 80], 
'Student_ID': [119, 119, 130, 140, 155, 155, 155], 
'ATAR': [80.0, 20.0, np.nan, 50.0, 15.0, np.nan, np.nan]
}).reindex_axis(['Student_ID','International','marks','ATAR'], axis=1)

print (df)
   Student_ID International  marks  ATAR
0         119             N     60  80.0
1         119             N     70  20.0
2         130             N     75   NaN
3         140             Y     78  50.0
4         155             Y     60  15.0
5         155             Y     85   NaN
6         155             Y     80   NaN

需要Series.nunique主要与boolean indexingloc一起返回一个列(Series),返回新df1的最后一个drop_duplicates

代码语言:javascript
复制
print(df['Student_ID'].nunique())
4
print(df.loc[df['International'] == 'N', 'Student_ID'].nunique())
2
print(df.loc[(df['International'] == 'N') & (df['ATAR'].notnull()), 'Student_ID'].nunique())
1
print(df.loc[df['ATAR'].between(0,50), 'Student_ID'].nunique())
3

df1 = df.drop_duplicates('Student_ID')
print (df1)
   Student_ID International  marks  ATAR
0         119             N     60  80.0
2         130             N     75   NaN
3         140             Y     78  50.0
4         155             Y     60  15.0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43511828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档