totolow
totolow

Reputation: 103

Calculate delta columns within one dataframe

I have a dataframe labeled as following:

a_col1 a_col2 a_col3 ID name b_col1 b_col2 b_col3

I am trying to generate new columns delta1, delta2, delta3

delta1 = b_col3 - a_col3
delta2 = b_col2 - a_col2
delta3 = b_col1 - a_col1

I currently use df['delta3'] = df['b_col3'] - df['a_col3']

Is there any easy way to create a loop that I don't have to iterate through col1 to col3

Upvotes: 1

Views: 47

Answers (3)

Quang Hoang
Quang Hoang

Reputation: 150745

Try with:

df[['delta1','delta2','delta3']] = df.filter(like='a_').sub(df.filter(like='b_').values)

Upvotes: 1

piRSquared
piRSquared

Reputation: 294318

eval

Separated string assignments with newline

evalstr = """\
delta1 = a_col1 - b_col1
delta2 = a_col2 - b_col2
delta3 = a_col3 - b_col3
"""
df.eval(evalstr)

   a_col1  a_col2  a_col3    ID  name  b_col1  b_col2  b_col3  delta1  delta2  delta3
0      10       9       8  this  that       5       6       7       5       3       1

Setup

df = pd.DataFrame({
    'a_col1': [10], 'a_col2': [9], 'a_col3': [8],
    'ID': ['this'], 'name': ['that'],
    'b_col1': [5], 'b_col2': [6], 'b_col3': [7],
})

Upvotes: 0

smci
smci

Reputation: 33950

So your a_col* columns have indices 0..2, b_col* are 5..7 and delta* will be 8..10

# Create new columns, na for pessimism
df[['delta1','delta2','delta3']] = np.nan

# Now compute their values
for i in range(3):
    df.iloc[:, 8+i] = df.iloc[:, 5+i] - df.iloc[:, i]

Really you could do the latter in one vectorized assignment:

df.iloc[:, [8,9,10]] = df.iloc[:, [5,6,7]] - df.iloc[:, [0,1,2]]

or just:

df[['delta1','delta2','delta3']] = df.iloc[:, [5,6,7]] - df.iloc[:, [0,1,2]]

Upvotes: 0

Related Questions