【问题标题】:How to sum up the columns of a pandas dataframe according to the elements in one of the columns [duplicate]如何根据其中一列中的元素总结熊猫数据框的列[重复]
【发布时间】:2018-04-21 05:53:52
【问题描述】:

我有一个这样的 csv 文件:

squareid       nofcolumns  callduration
3959_3_3       3.990301    997.056881
3961_2_2       7.996370   1153.932142
3961_2_3_0     5.345003    760.179554
3961_2_3_1     5.064245   1341.673636
3961_2_3_2    16.816554   2926.182896
3961_2_3_3_0   3.116286    351.698031
3961_2_3_3_1   7.269828   1842.511559
3961_3_2      10.944895   6865.086506
3962_0_1_0     3.116931    674.581507
3962_0_2       8.272328   4330.343234
3962_0_3       3.079968    279.802874
3962_1_0_0     4.015021    344.013988
3962_2_0_1     3.787312   1820.223512
3962_3_1       4.263979    657.806411
3962_3_2_2     4.184289    266.976026
3962_3_3_2     4.797507   1537.279123
3963_1_3_0     7.594542    545.348282
3963_1_3_3     3.845666    186.378080
3963_3_1_2_2   3.350109    505.276355
3963_3_1_2_3   3.229853    302.434752
...

我想根据squareid列对nofcallscallduration这两列进行聚合,并将结果文件写入一个新的csv文件。

这部分我尝试的是:

sub_df = sub_df.groupby('squareid').sum()
sub_df.to_csv(filename2,sep = '\t',header = False,index = False)

聚合有效,但在生成的文件中缺少squareid 列。

如何像原来指定squareid列的文件一样写?

【问题讨论】:

  • 如果你说index=True怎么办?
  • 使用df.groupby('squareid', as_index=False).sum(),因为groupby默认将分组列转换为索引,然后您在保存时将其省略。
  • @JohnZwinck 啊,非常感谢,是的,它成功了!我的问题解决了。
  • @JohnZwinck 只是指出,我不是反对者,但有一个 war raging 可以解释附带损害。

标签: python pandas dataframe


【解决方案1】:

您只需说出index=True 即可保存索引,而不是您当前的index=False

【讨论】:

  • 不是 index=True 默认值,因此 OP 可以删除它
  • 是的,它也很好用。谢谢。
猜你喜欢
  • 2020-04-26
  • 2021-05-04
  • 2019-02-12
  • 1970-01-01
  • 2020-03-26
  • 2012-06-19
相关资源
最近更新 更多