[英]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) “标题”(特定机器人的名称)位于 A 列和名为“状态”的 D 列(其中状态为已完成或失败)
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?如何计算 A 列中特定机器人的出现次数,条件是 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
:只需在value_counts
之前切片:
df.loc[df['Status'].eq('Completed'), 'Title'].value_counts()
Output:输出:
Robot1 2
Robot3 1
Name: Title, dtype: int64
Use groupby() with size() :使用 groupby() 和 size() :
condition = df['Status']=='completed'
result = df[condition].groupby('Title').size()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.