pythonpandasdataframe

How to sum up a particular row of number inputs in a DataFrame


I want to add the inputs in a particular row of data frame as total. But the output is

XYZ: OBJECT1 Object2
NUMBERS: 1 2

Where the inputted XYZ are Object2 and OBJECT1 and the inputted Numbers are 1 and 2 I want the output to be only the data frame and total of 1 and 2 Numbers (i.e. 1+2=3) so far I have tried

import pandas as pd
list=[]
n= input("ENTER THE NUMBER OF THINGS\n")
do=int(n)
for i in range(do):
    c=input("OBJECTS\n")
    list.append(c)
list2=[]
for i in range(do):
    c1=input("PRICE\n")
    list2.append(c1)
dd=pd.DataFrame([list , list2], index=["OBJECTS", "PRICE"], columns=[str(i+1) for i in range (do)])
print (dd)
total= dd.sum(axis=1)
print(total)

I want the output to be only the dataframe and total of 1 and 2 Numbers (i.e. 1+2=3)


Solution

  • Right now, you’re building your DataFrame with both objects and prices in the same orientation (as rows). That makes the "PRICE" row full of strings (since input() returns strings), so pandas can’t sum them as numbers — it concatenates instead.

    **corrected code: **

    import pandas as pd
    
    objects = []
    prices = []
    
    n = int(input("ENTER THE NUMBER OF THINGS\n"))
    for i in range(n):
        obj = input("OBJECTS\n")
        objects.append(obj)
        price = float(input("PRICE\n"))   # convert to numeric
        prices.append(price)
    
    # Make dataframe with each object as a row
    df = pd.DataFrame({
        "OBJECTS": objects,
        "PRICE": prices
    })
    
    # Calculate total
    total = df["PRICE"].sum()
    
    print(df)
    print("TOTAL:", total)