gpt4 book ai didi

python - 将 DataFrame 的列设置为 pandas 中另一个列的总和

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:06 25 4
gpt4 key购买 nike

我有一个如下所示的 DataFrame,称之为“值”:

enter image description here

我想创建另一个,称之为“sums”,它包含从“sums”中的列到末尾的 DataFrame“值”的总和。它看起来像下面这样:

enter image description here

我想在不逐个数据点查看整个 DataFrame 的情况下创建它。我一直在尝试使用 .apply() 如下所示,但我不断收到错误消息:unsupported operand type(s) for +: 'int' and 'datetime.date'

In [26]: values = pandas.DataFrame({0:[96,54,27,28],
1:[55,75,32,37],2:[54,99,36,46],3:[35,77,0,10],4:[62,25,0,25],
5:[0,66,0,89],6:[0,66,0,89],7:[0,0,0,0],8:[0,0,0,0]})

In [28]: sums = values.copy()

In [29]: sums.iloc[:,:] = ''

In [31]: for column in sums:
...: sums[column].apply(sum(values.loc[:,column:]))
...:
Traceback (most recent call last):

File "<ipython-input-31-030442e5005e>", line 2, in <module>
sums[column].apply(sum(values.loc[:,column:]))
File "C:\WinPython64bit\python-3.5.2.amd64\lib\site-packages\pandas\core\series.py", line 2220, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1088, in pandas.lib.map_infer (pandas\lib.c:63043)

TypeError: 'numpy.int64' object is not callable


In [32]: for column in sums:
...: sums[column] = sum(values.loc[:,column:])

In [33]: sums
Out[33]:
0 1 2 3 4 5 6 7 8
0 36 36 35 33 30 26 21 15 8
1 36 36 35 33 30 26 21 15 8
2 36 36 35 33 30 26 21 15 8
3 36 36 35 33 30 26 21 15 8

有没有办法不用单独循环每个点来做到这一点?

最佳答案

无需循环,您可以反转数据帧,每行 cumsum 然后重新反转它:

>>> values.iloc[:,::-1].cumsum(axis=1).iloc[:,::-1]
0 1 2 3 4 5 6 7 8
0 302 206 151 97 62 0 0 0 0
1 462 408 333 234 157 132 66 0 0
2 95 68 36 0 0 0 0 0 0
3 324 296 259 213 203 178 89 0 0

关于python - 将 DataFrame 的列设置为 pandas 中另一个列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43004327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com