Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Sum() issues

My current data is organised into two data frames of the same shape. Id then like to sum all columns into a single column after calculation.

I am doing this using:

    df = df1_kwh.multiply(df2np).sum(axis=1)

However when I use df.shape i get a shape of "(347,)" meaning no columns and I am then unable to add additional columns to the "sum" value column using df.insert.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What can I do to make the output of df.sum able to be manipulated by other functions?

>Solution :

If you want a DataFrame you can convert from Series using to_frame:

df = df1_kwh.multiply(df2np).sum(axis=1).to_frame()

By default the column name is 0, to change it (for example to "sum"), use:

df = df1_kwh.multiply(df2np).sum(axis=1).to_frame('sum')

Example:

np.random.seed(0)
df1_kwh = pd.DataFrame(np.random.random(size=(5,5)))
df2np = 2

df = df1_kwh.multiply(df2np).sum(axis=1).to_frame('sum')
df.insert(0, 'new', 'x')

output:

  new       sum
0   x  5.670608
1   x  6.644717
2   x  5.770594
3   x  5.176273
4   x  6.276120
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading