specmer specmer - 6 months ago 31
Python Question

Sum Each Column of CSV file

I have a large CSV file with 32 column headers. I'd like to sum up each column and the result be 32 individual summations of each column header. I have access to both python and powershell. Any help would be appreciated.

The furthest I got was this site: pandas groupby with sum() on large csv file?

Answer
import pandas as pd
pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum().values

Pandas is definitly the way to go . these two lines of code will print out the sum of the columns. if you are on windows use a '\' for specifying your path. I assume your csv file uses a semicolon as a seperator (if its a comma use sep=',' if its a tab use sep='\t')

If you want to write the result to a file use:

import pandas as pd
df = pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum()
df.to_csv(r'my_path_to_file/my_file_sum.csv')
Comments