【问题标题】:Calculate sum of donation money based on value in other column in pandas根据 pandas 中其他列的值计算捐款总额
【发布时间】: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


【解决方案1】:

这是一个精简的示例,但应该可以满足您的需求

df = pd.DataFrame({'occupation':['real estate','real estate','real estate','banker','baker'], 'donation':range(11,16)})

    occupation  donation
0  real estate        11
1  real estate        12
2  real estate        13
3       banker        14
4        baker        15

# filter on occupation
df[df['occupation']=='real estate']

    occupation  donation
0  real estate        11
1  real estate        12
2  real estate        13

# sum of all donations
df[df['occupation']=='real estate']['donation'].sum()

36

# count of all donations
df[df['occupation']=='real estate']['donation'].count()

3

分组比较

df.groupby('occupation').sum()

             donation
occupation
baker              15
banker             14
real estate        36

df.groupby('occupation').count()

             donation
occupation
baker               1
banker              1
real estate         3

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多