Victor
Victor

Reputation: 23

How to calculated pivot table using python

I have a sample table below:

Temperature Voltage     Data
25              3.3     2.15
25              3.3     2.21
25              3.3     2.23
25              3.3     2.26
25              3.3     2.19
25             3.45      2.4
25             3.45     2.37
25             3.45     2.42
25             3.45     2.34
25             3.45     2.35
105             3.3      3.2
105             3.3     3.22
105             3.3     3.23
105             3.3     3.24
105             3.3     3.26
105            3.45     3.33
105            3.45     3.32
105            3.45     3.34
105            3.45      3.3
105            3.45     3.36

I would like to calculate the average Data for each Temperature and Voltage case. I could do this in excel by making a pivot table but I would like to learn how to do it in python script so I can automate this data processing part.

Thank you, Victor

P.S. sorry for the weird format table. I'm not exactly sure how to correctly copy and paste a table in here.

Upvotes: 1

Views: 113

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18367

I think the function you need is .groupby() if you are familiar with it:

df.groupby(['Temperature','Voltage'])['Data'].mean()

This will generate a mean value of the value Data for each unique Temperature and Voltage combination. This is an example:

import pandas as pd
data = {
    'Temperature': [25,25,25,25,25,25,25,25,25,25,105,105,105,105,105,105,105,105,105,105],
    'Voltage': [3.3,3.3,3.3,3.3,3.3,3.45,3.45,3.45,3.45,3.45,3.3,3.3,3.3,3.3,3.3,3.45,3.45,3.45,3.45,3.45],
    'Data': [2.15,2.21,2.23,2.26,2.19,2.4,2.37,2.42,2.34,2.35,3.2,3.22,3.23,3.24,3.26,3.33,3.32,3.34,3.3,3.36]
}
df = pd.DataFrame(data)
print(df.groupby(['Temperature','Voltage'])['Data'].mean())

Output:

Temperature  Voltage
25           3.30       2.208
             3.45       2.376
105          3.30       3.230
             3.45       3.330

Upvotes: 3

Related Questions