简体   繁体   中英

Counting rows based on multiple conditions and add to list in pandas dataframe

I have a file which is needed for some summarizing statistics and I have a list of various robots and the status of their execution. My issue is that I've indexed them to a new dataframe using the following code:

x1 = df["Title"].value_counts().index.tolist()

I have several columns where eg. 'Title' (Name of specific robot) is in column A and a column D named 'Status'(where it either states Completed or Failed)

How do I count the number of occurrences of the specific robot in column A with the condition that is says completed in column D?

import pandas as pd
df = pd.DataFrame({'Title':['Robot1', 'Robot1', 'Robot3', 'Robot1', 'Robot3'], 'Status':['Completed', 'Failed', 'Running', 'Completed', 'Completed']})

print(df.to_string(index=False))

Title       Status
Robot1      Completed
Robot1      Failed
Robot3      Running
Robot1      Completed
Robot3      Completed

Just slice before value_counts :

df.loc[df['Status'].eq('Completed'), 'Title'].value_counts()

Output:

Robot1    2
Robot3    1
Name: Title, dtype: int64

Use groupby() with size() :

condition = df['Status']=='completed'
result = df[condition].groupby('Title').size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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