【发布时间】:2021-12-12 07:12:56
【问题描述】:
我正在尝试计算来自房地产行业的活动贡献数据的货币总和。
realestate_counter = 0
realestate_donations = 0
for row in range(df.shape[0]): #for each row in the dataframe
if 'realestate' in df.iloc[row]['Occupation']:
realestate_donations = realestate_donations + int(row)
print(df.iloc[row]['Amount'])
realestate_counter = realestate_counter + 1
# print('-------')
print('$' + str(realestate_donations) +' was doanted from the real estate industry.')
print('There are ' + str(realestate_counter) +' Real Estate donors.')
我的数据框有多种职业,但我只对房地产感兴趣。代码块打印职业为realestate的捐赠值并尝试求和。
我将print(df.iloc[row]['Amount]) 打印的数字粘贴到 Google 表格中并在其中求和。
这个数量与这行代码计算的数量大不相同ealestate_donations = realestate_donations + int(row)
谷歌表格:72200
我的代码:23973
我怀疑我的代码在某处出错,而 Google 表格是准确的。
我已经复制了下面的整个打印输出:
500.0
200.0
1000.0
1000.0
1000.0
1000.0
100.0
50.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
1000.0
-1000.0
1000.0
-1000.0
-1000.0
1000.0
1000.0
1000.0
1000.0
500.0
300.0
100.0
1000.0
1000.0
1000.0
1000.0
100.0
250.0
100.0
250.0
250.0
500.0
1000.0
$23973 was doanted from the real estate industry.
There are 88 Real Estate donors.
【问题讨论】:
-
我认为在 realestate_donation 中,你正在总结你想要的行的位置编号,就像你做的那样
+ int(row)和 row 似乎是索引号,也许你在realestate_donations = realestate_donations + int(df.iloc[row]['Amount'])之后。也就是说,这样的实现真的很慢,Jonathan Leon 的答案要好得多 -
这确实是问题所在。谢谢!
标签: python pandas dataframe data-cleaning