简体   繁体   English

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

[英]python pandas filter and aggregate multiple columns and write into CSV

I want to read a CSV file and count / aggregate on multiple columns 我想读取CSV文件并在多列上计数/聚合

My input data is as follows 我的输入数据如下

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

Am new to pandas and so far by reading various questions here looks like I need to use one or more of set_index(), .append(), , .join(), .agg() 对熊猫来说是新手,到目前为止通过阅读各种问题看起来我需要使用set_index(),. append(),.。join(),. gog()中的一个或多个

I have the individual results but cannot get the new results I want. 我有个别结果,但无法得到我想要的新结果。

import pandas as pd

df = pd.read_csv("flagdata.csv")

print (df["date"].value_counts())


df_flag1 = df[df.flag1 == True]
df_flag1  = df_flag1["date"].value_counts()
print (df_flag1)

df_flag2 = df[df.flag2 == True]
df_flag2 = df_flag2["date"].value_counts()
print (df_flag2)


df_flag3 = df[df.flag3 == True]
df_flag3 = df_flag3["date"].value_counts()
print (df_flag3)

I want to get a count of True Flags for each date to create a new csv file with the following result - date, total count, flag1 true count, flag2 true count, flag3 true count 我想获得每个日期的True Flags计数,以创建一个具有以下结果的新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

You need to group the rows by date and count and sum the flags: 您需要按日期对行进行分组并计算并对标记求和:

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')

groupby() and created new count field reset_index as "count" then in seconf df groupby for sum of all True groupby()并将新计数字段reset_index创建为“count”,然后在seconf df groupby中创建所有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)

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

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