【问题标题】:Pandas: aggregate sum showing list熊猫:总和显示列表
【发布时间】:2019-04-03 17:28:08
【问题描述】:

我在让 pandas 汇总和求和时遇到问题。

文件样本:

18820   Multiple choice / by Zambra, Alejandro, ZAMBRA  B   F   15.00   15.00
18821   Green girl / by Zambreno, Kate, ZAMBREN B   F   15.00   15.00
18822   Milena, or, The most beautiful femur in the wo...   ZEPEDA  B   F   19.00   19.00
18823   Death notice : by Zhou, Haohui, ZHOU    B   F   27.00   27.00
18824   Billy Pintos war / by Zimmer, Michael,  ZIMMER  B   F   26.00   26.00

我的代码:

print_itypes = df.loc[df['itype'].isin(['B','NB','CLUB',])]
print_stuff = print_itypes[pd.to_numeric(print_itypes['replacement_cost'], errors='coerce').notnull()]
print_stuff.groupby("itype").agg({"replacement_cost": np.sum})

输出:

B   30.0018.0023.0019.0018.0020.0020.0013.0028.002...
CLUB    5.0015.0015.0010.0010.0015.0017.0015.0010.008....
NB  17.9529.0029.0016.0016.0016.9515.0015.0015.002...

不求和,只是列表。我必须在等式中的某处使用to_numeric,否则,python 会窒息并抱怨 non_numeric ...等。没有这个我什么都做不了。

【问题讨论】:

  • print_stuff['replacement_cost']=print_stuff['replacement_cost'].astype(float) 然后执行代码..??
  • @anky_91成功了!如果您想将其设置为答案,我将选中它。谢谢!!
  • @anky_91 绿色检查!再次感谢,这正是我所需要的。

标签: python pandas jupyter


【解决方案1】:

似乎replacement_cost 列是一个字符串,因此sum() 连接值而不是求和。

尝试类似:

print_stuff['replacement_cost']=print_stuff['replacement_cost'].astype(float)

这会将replacement_cost 列转换为浮点数并发布groupby().sum() 将按预期工作。

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2019-05-20
    • 1970-01-01
    • 2017-01-14
    • 2014-02-19
    • 2018-11-08
    • 2017-07-03
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多