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