我想在 Pandas 数据框中创建一列,该列将添加其他列的值(0 或 1)。该列称为“总和”我的 HEADPandas 看起来像: Application AnsSr sum Col1 Col2 Col3 .... Col(n-2) Col(n-1) Col(n)date 28-12-11 0.0 0.0 28/12/11 .... ...Dates... 28/12/11~00c 0 0.0 0.0 0 0 0 .... 0 0 0~00pr 0 0.0 0.0 0 0 0 .... 0 0 0~00te 0 0.0 0.0 0 0 1 .... 0 0 1在来自 pythoneverywhere 的图像中:预期结果(假设没有更多的列 Application AnsSr sum Col1 Col2 Col3 .... Col(n-2) Col(n-1) Col(n)date 28-12-11 0.0 nan 28/12/11 .... ...Dates... 28/12/11~00c 0 0.0 0.0 0 0 0 .... 0 0 0~00pr 0 0.0 0.0 0 0 0 .... 0 0 0~00te 0 0.0 2 0 0 1 .... 0 0 1如您所见,即使某些列中有 1 个值,“sum”的值也保持为 0。我究竟做错了什么?代码的基础是:theMatrix=pd.DataFrame([datetime.today().strftime('%Y-%m-%d')],['Date'],['Application'])theMatrix['Ans'] = 0theMatrix['sum'] = 0到目前为止一切顺利,然后我用 loc 添加所有值。然后我想把值加起来theMatrix.fillna(0, inplace=True)# this being the key line:theMatrix['sum'] = theMatrix.sum(axis=1)theMatrix.sort_index(axis=0, ascending=True, inplace=True)正如您在结果(附图)中看到的,总和仍然为 0。我查看了此处或此处以及 Pandas文档,但无济于事。其实表达的是:theMatrix['sum'] = theMatrix.sum(axis=1)我从那里得到的。通过以下方式更改最后一行:theMatrix['sum'] = theMatrix[3:0].sum(axis=1)为了避免对前三列求和,结果如下: Application AnsSr sum Col1 Col2 Col3 .... Col(n-2) Col(n-1) Col(n)date 28-12-11 0.0 nan 28/12/11 .... ...Dates... 28/12/11~00c 0 0.0 nan 1 1 0 .... 0 0 0~00pr 0 0.0 1.0 0 0 0 .... 0 0 1~00te 0 0.0 0 0 0 0 .... 0 0 0请注意两件事:a) 行 '~00c' 中的总和如何为 nan 但该行中有 1。b) 在计算总和之前,代码 theMatrix.fillna(0, inplace=True) 应该将所有可能的 nan 更改为 0,因此总和不应该是 nan,因为理论上在任何列中都没有 nan 值 [3: ]它不会工作。一些想法?
添加回答
举报
0/150
提交
取消