简体   繁体   中英

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:

Col1   Col2

0      217
287    130

I'm trying to subtract the two numbers inside column 2

If you are trying to do subtraction between all of the elements in Col2, you can do:

sub = df['Col2'].diff()

sub will be a Series where:

Col2

NaN
-87

DataFrame.diff()

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]

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM