python - cumsum() 在多个列上

标签 python pandas dataframe cumsum

我想创建以下数据框:

Index       A        B        C
 a          0        0        0
 b          1       10        0
 c         -1        0      -10
 d          1       20        0
 e          0        0        0
 f         -1        0      -20
 g          0        0        0
 h          1       15        0
 i         -1        0      -15

AB 已给出。 C 应通过函数生成,无需迭代。可能以这种方式:

def generate_C():
    C = np.where(A == -1, << here prior value from B * -1 >>, 0)
    df['C] = C
    return df

我尝试通过 cumsum() 处理 BC 列,但效果不佳。有什么建议吗?

最佳答案

您可以使用:

df.loc[df.A==-1, 'C'] = (-df.loc[df.A==1, 'B']).values
df.C.fillna(0, inplace=True)
print (df)
       A   B    C   
Index                 
a      0   0   0.0
b      1  10   0.0
c     -1   0 -10.0
d      1  20   0.0
e      0   0   0.0
f     -1   0 -20.0

关于python - cumsum() 在多个列上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37607822/

相关文章:

python - Pandas:相互评估两个数据帧

python - 使用 ~isin([list_of_substrings]) 过滤 Dataframe

python - 难以使用具有不同格式字符串的 Python struct.Struct.unpack_from

Python MySQLdb 占位符语法

python - Pandas 数据帧到 JSON 格式的操作

Python pandas groupby 箱线图重叠

python - 使用 Python 客户端使用 GAE 端点

python - Python 和 Rubular 之间正则表达式的区别?

pandas - 根据列中的信息过滤出化学数据集

python - Pandas 数据框列标题到数据标签