[英]Python/Pandas subtracting numbers in a column
Sorry if this is a dumb question, 对不起,如果这是一个愚蠢的问题,
I have a pandas data frame that looks kind of like this: 我有一个像这样的pandas数据框:
Col1 Col2
0 217
287 130
I'm trying to subtract the two numbers inside column 2 我试图减去第2列中的两个数字
If you are trying to do subtraction between all of the elements in Col2, you can do: 如果您尝试在Col2中的所有元素之间进行减法,则可以执行以下操作:
sub = df['Col2'].diff()
sub will be a Series where: sub将是一个系列,其中:
Col2
NaN
-87
If i understand you question you want to do this: 如果我理解你的问题,你想这样做:
res = dataFrame['Col2'][0] - dataFrame['Col2'][1]
If this is not what you are asking please fix you question or comment below. 如果这不是您要求的,请在下面修改您的问题或评论。
You can .sum()
the values in the columns and subtract that value from the first value at df.loc[0]
你可以
.sum()
列中的值,并从df.loc[0]
的第一个值中减去该值
df
Col1 Col2
0 0 217
1 278 130
df.loc[0] - df.loc[1:].sum()
The output: 输出:
Col1 -278
Col2 87
dtype: int64
If you only want to apply this to Col2
: 如果您只想将其应用于
Col2
:
df['Col2'].loc[0] - df['Col2'].loc[1:].sum()
Output: 输出:
87
You can use this on any number of rows in your data frame: 您可以在数据框中的任意数量的行上使用它:
Col1 Col2
0 0 217
1 278 130
2 23 45
3 22 123
4 370 123
df.loc[0] - df.loc[1:].sum()
Output: 输出:
Col1 -693
Col2 -204
dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.