Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建一列,该列是#上一列的总和_Python_Pandas_Dataframe - Fatal编程技术网

Python 创建一列,该列是#上一列的总和

Python 创建一列,该列是#上一列的总和,python,pandas,dataframe,Python,Pandas,Dataframe,我有这样一个数据帧结构: ###Date, A, B### 2020.06.10, 2, 3 我需要创建一个额外的列,它使用索引(不带df['A']或df['B'])对前两列求和 提前谢谢你 保罗 应该有效。n\u previous=2 df[“另一个”]=df.iloc[:,-n_previous:]和(轴=1) 取前面的n列并沿行轴求和,为什么不从df.columns cols = df.columns[-2:] df['new'] = df[cols].sum(axis=1) 使用d

我有这样一个数据帧结构:

###Date, A, B###
2020.06.10, 2, 3
我需要创建一个额外的列,它使用索引(不带df['A']或df['B'])对前两列求和

提前谢谢你

保罗

应该有效。

n\u previous=2
df[“另一个”]=df.iloc[:,-n_previous:]和(轴=1)

取前面的n列并沿行轴求和,为什么不从
df.columns

cols = df.columns[-2:]
df['new'] = df[cols].sum(axis=1)

使用
df.iloc
对所有行进行切片,并将
nth
列转到
nth+2
列 在哪里

解释
df.iloc[:,n:n+2
的工作方式类似于python范围,列范围选择中的结束数字不包含在选择中

就你而言

n=1#starting column index
df['c']=df.iloc[:,n:n+2].apply(lambda x: x.sum(), axis=1)

Date           A    B   c
0   2020.06.10  2   3   5

Date
是索引还是其他列?是否有更多列?
cols = df.columns[-2:]
df['new'] = df[cols].sum(axis=1)
n=starting column, integer index
n+2=ending column, integer index
n=1#starting column index
df['c']=df.iloc[:,n:n+2].apply(lambda x: x.sum(), axis=1)

Date           A    B   c
0   2020.06.10  2   3   5