Danny Huber
Danny Huber

Reputation: 21

Pandas .sum() refuses to sum column properly

I have a bit of code here that is doing a few things, but most importantly summing a single particular column in a dataset.

    # Limit the values to be summed based on the IDL

for i in range(len(merge1)):
    print (" Checking Value Against IDL ")
    if float(merge1.iloc[i, 8]) <= float(merge1.iloc[i, 3]):        
        merge1.iloc[i, 8] = 0
    ###
merge1.columns =('CB #', 'PCB Homolog Group', 'Ref #', 'IDL ng mL', 'Target #', 'CB #_2', 'R.T. min', 'Response Sig.', 'Concentration', 'Units')
columns = merge1.columns
print (columns)
merge1.at['Total', 'Concentration'] = merge1.iloc[:, 8].sum()
print (merge1)
merge1.to_csv( CBReference_Dir + 'Export_Test_3.csv', index = None, header = True)

The .sum() should now sum the entire contents of the column at index position #8, but instead this is happening: enter image description here

All of the contents of each row in that column are simply being placed next to one-another in a single cell which I specified. They should be summed instead and the total should be around ~85. I'm lost and not sure how to get this column to sum properly, I have never run into this issue with pandas dataframes before...

Upvotes: 0

Views: 250

Answers (1)

Danny Huber
Danny Huber

Reputation: 21

A usable solution was:

merge1.at['Total', 'Concentration'] = sum(map(float, merge1['Concentration']))
print (merge1)

Using the map command I was able to apply the float class to each position in the column I desired to sum. From there, everything in that column was summed as expected.

Upvotes: 1

Related Questions