So i have a data frame with row labels as months and the columns are amounts in float format, i need to sum and multiply the columns in such a way, in which the numbers of rows when the code takes to calculate the sum changes are according to the user, which means the user should be able to take 12 months values 24 etc. The summation of the columns should be divided by the previous column, so the division should be Current_sum(Column) / Previous_sum(Column). The sum should be in such a way in which the code should exclude the last row of the DataFrame when it sums to 12 or 24 values according to user.
Thank you for the efforts in advance:)
import pandas as pd
Example data to simulate basedata2 (replace this with your actual basedata2)
data =basedata2
Create the dataframe
df = pd.DataFrame(data)
def calculate_sums_and_ratios(df):
# Initialize lists to store the sums
excluded_sums = []
total_sums = []
# Calculate the sums with exclusion and total sums for each column
for col in df.columns:
valid_values = df[col].dropna()
if len(valid_values) > 1:
col_sum_excluded = valid_values.iloc[:-1].sum()
else:
col_sum_excluded = 0
col_sum_total = valid_values.sum()
excluded_sums.append(col_sum_excluded)
total_sums.append(col_sum_total)
# Calculate the ratios, ensuring the logic continues for each column
ratios = []
for i in range(len(total_sums)):
if i == 0:
ratios.append(1)
else:
previous_excluded_sum = excluded_sums[i - 1]
current_total_sum = total_sums[i]
if previous_excluded_sum != 0:
ratio = current_total_sum / previous_excluded_sum
else:
ratio = None # Avoid division by zero
ratios.append(ratio)
# Create a dataframe for the results
result_df = pd.DataFrame([ratios], columns=df.columns)
return result_df
Call the function and print the result
result_df = calculate_sums_and_ratios(df)
print(result_df)
i tried this code but the code doesnt exclude the last row when it iterates through the columns, and it doesnt have the input function to take user input
Karthik Amballa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.