首页 > 解决方案 > 如何计算同一列的两个值的差异并使用结果添加新列

问题描述

在具有值 [1,2,4,4,5,5] 的 Excel 列 A 中。答案是新列 B: B2 = A2-A1= 1, B3=A3-A2=2, B4=A4-A3=0 我不介意为新列的第一行取 0

df = pd.DataFrame({'a':[6,2,4,5], 'b':[3,4,8,7]})

#Columnn c based off b 
df['c] = [0,1,4,-1]

# The first value is a zero by default in the new column 

不工作

df['c'] = df.apply(lambda x: x.d[n+1] - x.d[n], axis=1)

#Columnn c based off b from above
df['c] = [0,1,4,-1]

# The first value is a zero by default in the new column 

标签: pandasapply

解决方案


推荐阅读