Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有两列,我正在尝试使用 pandas 来计算它。我是一个电子表格用户,最近学习 python 进行快速计算。我想创建一个新列“C”,我只知道使用 excel 公式,但在 python 中,我知道计算两行值之间的差异。不知道如何在 pandas 中获得我期望的结果。
A B a r b m c f
试过:
df['C']=df['A'] - df['A'].shift(-1)
预期输出:
C (b-a) (c-b)
利用:
df['C'] = df['A'] - df['A'].shift()
或者:
df['C'] = df['A'].diff()
然后如果需要删除缺少值的第一行:
df = df.iloc[1:]
NaN或者如果第一行只有一个s:
NaN
df = df.dropna(subset=['A'])
就像MStaino评论一样,如果需要在差异后向上移动行(获取C列中的最后一个 NaN 值):
MStaino
C
df['C'] = df['A'].diff().shift(-1)