How to apply operation on each column in datafarme and assign it inbetween the column

Question:

I want to apply operations on every column in a dataframe.

original data frame

c0 c1. c2.
1 2 3
2 3 4

Operation

v1=[0,1,1,2,3,4,5]

opp=(previous_column-v1)

example for creating new column next to 1st column

opp=(previous_column-v1)
opp=(1-0)
opp=1

1st value in v1 is applicable to column 1, 2nd value for 2nd column and so on.

I tried the following code for last column


df[7]=(df[6]-5)

This creates column 7 and applies the operation. What I want is to create a new columns next to existing columns and apply operation on previous column

Expected output:

c0 c1 c2. c3. c4. c5.
1. (1-0)=1 2 (2-1)=1 3. (3-1)=2
2 (2-0)=1. 3. (3-1)=1. 4. (4-1)=3.
Asked By: user19810659

||

Answers:

IIUC, you can use:

v1=[0,1,1,2,3,4,5]

# define final order of columns
order = (np.tile([0,df.shape[1]], df.shape[1])
        +np.repeat(np.arange(df.shape[1]), 2)
        )

# subtract, concat, reorder
out = (pd.concat([df, df.sub(v1[:df.shape[1]]).add_suffix('_op')],
                 axis=1)
         .iloc[:, order]
       )

print(out)

Output:

   c0  c0_op  c1  c1_op  c2  c2_op
0   1      1   2      1   3      2
1   2      2   3      2   4      3

If you rather want a new column index:

v1=[0,1,1,2,3,4,5]

# define final order of columns
order = (np.tile([0,df.shape[1]], df.shape[1])
        +np.repeat(np.arange(df.shape[1]), 2)
        )

# subtract, concat, reorder
out = (pd.concat([df, df.sub(v1[:df.shape[1]])],
                 axis=1, ignore_index=True)
         .iloc[:, order].set_axis(range(df.shape[1]*2), axis=1)
       )

Output:

   0  1  2  3  4  5
0  1  1  2  1  3  2
1  2  2  3  2  4  3
Answered By: mozway
pd.concat([pd.DataFrame(df1.to_numpy()),pd.DataFrame(df1.to_numpy()-v1[:len(df1.columns)])],axis=1)
    .sort_index(axis=1).set_axis("c0    c1  c2. c3. c4. c5.".split("t"),axis=1)

out:

   c0  c1  c2.  c3.  c4.  c5.
0   1   1    2    1    3    2
1   2   2    3    2    4    3
Answered By: G.G
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.