Home > Software engineering >  Calculate sum of a Dataframe column
Calculate sum of a Dataframe column

Time:05-30

import pandas as pd
data = {
    "X" : [1, 3, 10, 16, 26, 36],
    "Y" : [42, 50, 75, 100, 150, 200]
}

df = pd.DataFrame(data)

I want to print sum of X. sum_of_X = df[0].sum() won't work.

How can I solve this?

CodePudding user response:

Do you mean something like this?

import pandas as pd
data = {
    "X" : [1, 3, 10, 16, 26, 36],
    "Y" : [42, 50, 75, 100, 150, 200]
}

df = pd.DataFrame(data)
print(df["X"].sum())

Which gives me 92

CodePudding user response:

You can use the Python way and just sum(df['X']) or even sum(data['X']) (You don't really need to crate the dataframe at all for that)

Or you can use pandas' built-in and use df['X'].sum()

CodePudding user response:

Do you need a dataframe?

sum(data['X']) 
  • Related