简体   繁体   English

试图将 countif function 从 excel 复制到 python

[英]Trying to replicate countif function from excel to python

I'm trying to get the below required output in python我正在尝试在 python 中获取以下所需的 output

Input:输入:

S.No      Name         Marks     
1        Jack           85       
2        Ram            75       
3        Jack           86
4        Ann            90

Required Output:所需 Output:

S.No      Name         Marks     Count     
1        Jack           85       2
2        Ram            75       1
3        Jack           86       2
4        Ann            90       1

i tried the below code to add the count column which is similar to excel workings using countif function '''我尝试使用以下代码添加类似于 excel 工作原理的计数列,使用 countif function '''

data['count']=data['Name'].value_counts()

''' this code gives the below output ''' 此代码给出以下 output

S.No      Name         Marks     Count     
1        Jack           85       NaN
2        Ram            75       NaN
3        Jack           86       NaN
4        Ann            90       NaN

I'm not sure what is missing, Can someone help me in this?我不确定缺少什么,有人可以帮助我吗? Really appreciate your help.非常感谢您的帮助。

You can get what you need with groupby and transform :您可以使用groupbytransform获得所需的内容:

df['count'] = df.groupby('Name')['Name'].transform('size')

which prints:打印:

   S.No  Name  Marks  count
0     1  Jack     85      2
1     2   Ram     75      1
2     3  Jack     86      2
3     4   Ann     90      1

Try this:尝试这个:

df.merge(df.groupby('Name').count(), on='Name').loc[:,:'S.No_y'].rename(columns={'S.No_x':'S.No', 'Marks_x':'Marks', 'S.No_y':'Count'}).set_index('S.No').sort_index()

      Name  Marks  Count
S.No
1     Jack     85      2
2      Ram     75      1
3     Jack     86      2
4      Ann     90      1

Try this:尝试这个:

import pandas as pd
import numpy as np

df =\
pd.DataFrame([["1","2","3","4"],
              ["Jack","Ram","Jack","Ann"],
              [85,75,86,90]] ).T  

df.columns = ["S.No","Name","Marks"]  
df.set_index("S.No", inplace=True) 
names_count = df.groupby("Name").size().rename("Count")
df = df.merge(names_count, on="Name", right_index=True)

print(df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM