Hello everyone! i am new to coding, and am trying to work on a script which uses information to calculate home many grams or micrograms a categorey contains based on the user imput. The below script works perfectly for any input besides one. when the user enters 1 as a choice, i get the following error code on the last line of the script: AttributeError: 'float' object has no attribute 'sum' what do i do to change this?
filename = '/Users/chelsie/Desktop/20220503_python_input_template.csv'
df = pd.read_csv(filename,delimiter=';',decimal=',',na_values=-9999.99)
# define columns, 1st line is header
cat = df["Category"]
subcat = df["Sub-category"]
m_p = df["mass per item (g)"]
m_mp = df["mass micrograms per item (g)"]
freq = df["Frequency as factor"]
#calculating number of children
print("Do You have any children?\n1) No\n2) Yes- 1\n3) Yes-2\n4) Yes-3")
val1 = int(input("Enter value: "))
# find all rows that contain a certain string
info = df.loc[cat.str.contains("Children", case=False)]
idx=df.index[cat=='Children']
if val1 == 1:
child=0.
total+=0.
elif val1 == 2:
child=1.
#for i in range(len(idx)):
total+= m_p.iloc[idx] *freq.iloc[idx]
elif val1 == 3:
child=2.
total += m_p.iloc[idx] *freq.iloc[idx]
elif val1 == 4:
child=3.
total += m_p.iloc[idx] *freq.iloc[idx]
else:
print('error')
total = total.sum()*child
# #calculate number of grams per child
这可能是因为在m_p != 1
情况下, total
是一些具有 .sum() 方法的熊猫对象,而在val1 == 1
情况下, total
是浮点数(浮点数没有 .sum() 方法)。
in the other conditions, you have the line total += m_p.iloc[idx]...
. Here, m_p.iloc[]
returns a Pandas Series . When this line is executed, the total
variable now holds a Pandas Series object which has a .sum()
method.
But in the first condition, you are just adding a float to total
. The total
variable remains a float variable which of course doesnt have a .sum()
method. The exact error you are getting.
To fix this, you can initialize total
as a Series :
total = pd.Series([0.])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.