python pandas过滤并聚合多个列并写入CSV

2024-06-28 18:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读取一个CSV文件并对多个列进行计数/聚合

我的输入数据如下

unique_identifier,date,flag1,flag2,flag3
a1,7/1/2017,FALSE,TRUE,FALSE
a2,7/1/2017,FALSE,TRUE,FALSE
a3,7/1/2017,FALSE,TRUE,FALSE
a4,7/1/2017,TRUE,FALSE,FALSE
a5,7/1/2017,FALSE,FALSE,FALSE
a6,7/2/2017,FALSE,FALSE,TRUE
a7,7/2/2017,FALSE,FALSE,TRUE
a8,7/2/2017,FALSE,TRUE,FALSE
q9,7/2/2017,FALSE,TRUE,TRUE

我对pandas还不熟悉,到目前为止,通过阅读这里的各种问题,我似乎需要使用一个或多个set_index(),.append(),.join(),.agg()

我有单独的结果,但不能得到我想要的新结果。在

^{pr2}$

我想得到每个日期的真标志计数,以创建一个新的csv文件,结果如下:date,total count,flag1 True count,flag2 True count,flag3 True count

date,count,flag1,flag2,flag3
7/1/2017,5,1,3,0
7/2/2017,4,0,2,3

Tags: 文件csv数据falsetruedatea1count
2条回答

groupby()并创建新的count字段将索引重置为“count”,然后在第二个dfgroupby中为所有True中的sum

df1= df.groupby("date")["date"].count().reset_index(name="count")
df2= df.groupby("date").sum().astype(int).reset_index()
df3 = pd.merge(df1,df2, on="date")
df3.to_csv("output.csv",index=False)

您需要按日期对行进行分组,并对标志进行计数和求和:

result = pd.concat([df.groupby('date').count()['flag1'],
                    df.groupby('date').sum()], 
                    axis=1).astype(int)
result.columns = ['count'] + result.columns[1:].tolist() 
#          count  flag1  flag2  flag3
#date                                
#7/1/2017      5      1      3      0
#7/2/2017      4      0      2      3

result.to_csv('output.csv')

相关问题 更多 >