I have a python dataframe that looks like the excel image below. I would like to add a single cell on the bottom corner that contains the sum. I'm certain that someone else has asked this question but I can't seem to find the answer. If anyone could help me with the code needed to place that sum item in the same location as below or direct me to a similar question I'd greatly appreciate it. I have a feeling that I'm not searching for the right term but I don't know what that term would be. Thanks in advance!
CodePudding user response:
This isn't the best way to use a pandas DataFrame but if you need to do it anyway then here is one way you can do it:
import pandas as pd
# Create your dataframe
df = pd.DataFrame({'A': ['Jerry', 'Tom', 'Larry', 'Jill'],
'B': [5, 8, 12, 4]})
# Add empty line at the bottom
df.loc[len(df)] = [pd.NA] * len(df.columns)
# Add a column containing the sum
df2 = pd.DataFrame({'C': [pd.NA] * (len(df)-1) [df.B.sum()]})
df.join(df2)
Result:
|A |B |C |
|-----|----|----|
|Jerry|5 |<NA>|
|Tom |8 |<NA>|
|Larry|12 |<NA>|
|Jill |4 |<NA>|
|NaN |<NA>|29 |
Again this is not how you should use DataFrames. If you want to display your data you maybe want to try using plotly tables instead.