简体   繁体   中英

Average of Subset of Values in a Dataframe

I have a dataframe which has the 3 columns

Date    Col 2     Col 3
10/1/19    C1        0.5
10/1/19    C2        0.3
10/1/19    C3        0.2
10/1/19    C1        0.5
10/1/19    C2        0.3 
10/1/19    C3        0.2
10/2/19    C1        0.5
10/2/19    C2        0.3
10/2/19    C3        0.2
10/2/19    C1        0.5
10/2/19    C2        0.3 
10/2/19    C3        0.2
...
12/13/19   C3        0.5

I would like to calculate the Average of each Unique value in Col 2 for each day with the avg of Col 3.

So for example,

Date       Col 2       Col3 (Avg)
10/1/19       C1         0.2
10/1/19       C2         0.4
10/1/19       C3         0.3
10/2/19       C1         0.2
10/2/19       C2         0.1
...

I am new to python and have tried doing this in Pandas but I am not able to figure it out. Any help is appreciated. I am able to get the average of the entire column but not the subset.

You want GroupBy.mean :

df.groupby(['Date', 'Col 2'], as_index=False)['Col 3'].mean()

    Date   Col 2  Col 3
0  10/1/19   C1   0.5
1  10/1/19   C2   0.3
2  10/1/19   C3   0.2
3  10/2/19   C1   0.5
4  10/2/19   C2   0.3
5  10/2/19   C3   0.2

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