Why keyerror when header is in df - renamed header but same keyerror

Viewed 34

While working on a summery of data from train passages I would like to .sum() the monthly df from a sensor. Target is the df "Total weight (T)" column.

           Date Total weight (T)  Axle passages  ...  Average speed (km/h) 
0   2022-07-01         95652.12           6048  ...                 53.31  
1   2022-07-02        111260.02           6558  ...                 53.16  
2   2022-07-03         93814.35           5774  ...                  54.5  
3   2022-07-04        121471.96           7314  ...                 53.26   
...shortened...

Trying to go for month_tot_weight = df.loc['Total weight (T)].sum() but ended with keyerror because Total weight (T) is not an key to be found in the df.
Tryed this renaming solution...:

i = 0
for col in df.columns:
    print(config.summery_passage_columns_alias[i])
    print(col, "-", len(col))
    df. rename(columns = {col:str(config.summery_passage_columns_alias[i])}, inplace = True)
    i += 1

My config has a list containing alies for all coulmn headers and "Total weight (T)" is substituted with "Total"

total = df.sum(axis=0)
print("Total\n", total)
print(df.head())
  • but same problem occurs:
Total
 Date                     2022-07-012022-07-022022-07-032022-07-042022-0...
Total                                                            3105787.5
Axle_passages                                                       186121
Train_passages                                                        1034
Highest_speed_(km/h)                                               2006.37
...and so on

Seems like in this .sum of all columns each column can deliver a sum, but I get a keyerror when trying to get sum for one column...

Any suggestions :)

1 Answers

See https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html.

You are using only one argument, thus selecting dataframe index. You want to select a column.

Here are possible workarounds:

df['Total weight (T)'].sum()

here you select only 'Total weight (T)' column as a pd.Series, or

df.loc[:, 'Total weight (T)'].sum()

here you explicitly select all rows in 'Total weight (T)' column.

For more information, Pandas indexing is described here: https://pandas.pydata.org/docs/user_guide/indexing.html

Related