繁体   English   中英

尝试使用Python / pandas基于来自另一个数据帧的列的内部总和来创建新的数据帧

[英]Trying to create a new dataframe based on internal sums of a column from another dataframe using Python/pandas

我们假设我有一个pandas数据帧df,如下所示:

df = DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]})

    Col1 Col2
0      1      5
1      2      6
2      3      7
3      4      8

有没有办法让我将列更改为列中所有以下元素的总和?

例如,对于'Col1',结果将是:

    Col1   Col2
0     10      5
1      9      6
2      7      7
3      4      8

1变为1 + 2 + 3 + 4 = 10
2变为2 + 3 + 4 = 9
3变为3 + 4 = 7
4仍然是4

如果这是可能的,有没有办法让我指定一个截止索引,之后会发生这种行为? 例如,如果截止索引是键1,结果将是:

    Col1   Col2
0      1      5
1      2      6
2      7      7
3      4      8

我在想除了使用循环之外别无他法,但我认为可能有一种方法可以使用矢量化计算。

谢谢堆

是的,你可以使用循环但非常便宜的:

def sum_col(column,start=0):
    l = len(column)
    return [column.values[i:].sum() for i in range(start,l)]

用法:

data['Col1'] = sum_col(data['Col1'],0)

这是一种避免循环的方法。

import pandas as pd

your_df = pd.DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]})

def your_func(df, column, cutoff):
    # do cumsum and flip over
    x = df[column][::-1].cumsum()[::-1]
    df[column][df.index > cutoff] = x[x.index > cutoff]     
    return df

# to use it
your_func(your_df, column='Col1', cutoff=1)

Out[68]: 
   Col1  Col2
0     1     5
1     2     6
2     7     7
3     4     8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM