简体   繁体   中英

How to subtract the columns after the first column, from the first column in a loop?

It seems simple but I can't seem to find an efficient way to solve this in Python 3: Is there is a loop I can use in my dataframe that subtracts every column after the first column, from the first column, so that I can add that new subtracted column to a new dataframe?

Then I would like to move on to subtract every column after the second column, from the second column, and follow the same logic throughout the 18 columns where I append or add that new subtracted column to the new dataframe

Here are first 4 lines of code for the 1st and 2nd columns I am using to my dataframe (spotrates), but I have 18 columns and I know it would be easier to create a loop, and I am adding on to the end of my existing dataframe, when I want the subtracted column to be inserted to a new one.

spotrates['3m-on'] = spotrates.iloc[:,1] - spotrates.iloc[:,0]
spotrates['6m-on'] = spotrates.iloc[:,2] - spotrates.iloc[:,0]
spotrates['9m-on'] = spotrates.iloc[:,3] - spotrates.iloc[:,0]
spotrates['1y-on'] = spotrates.iloc[:,4] - spotrates.iloc[:,0]

spotrates['6m-3m'] = spotrates.iloc[:,2] - spotrates.iloc[:,1]
spotrates['9m-3m'] = spotrates.iloc[:,3] - spotrates.iloc[:,1]
spotrates['1y-3m'] = spotrates.iloc[:,4] - spotrates.iloc[:,1]
spotrates['2y-3m'] = spotrates.iloc[:,5] - spotrates.iloc[:,1]

Here is a code I've started to work on inefficiently:

def swaps(data):
    i<len(data.columns)
    col1 = data.iloc[:,i]
    col2 = data.iloc[:,i+1]
    for col1, col2 in data.columns:
        return col2 - col1
        
        

I think you can use a (if you have a row for an id you can get your items by) select from where statement. make sure the 1 is whatever your first item's id is.

DELETE FROM mytable WHERE ID!=1

This will remove everything except the first row!

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