# Numpy arithmetic operation between two columns

Below is the numpy array. I need to perform two operations on this array.

1. Add one column with value [column 1] - [column 3].
2. Add another column with value [column 1] - [previous value of column1].

I can do this using normal list operations, but is it possible to use numpy or pandas? If so, how can it be done?

Input data:

[['78' '3412' '98' '3441']
['106' '3412' '127' '3434']
['139' '3411' '160' '3434']
['170' '3411' '191' '3442']
]


These types of operations can easily be done using both numpy or pandas. However, in this case I would recommend pandas since it is more intuitive. Using the example array we can create a pandas dataframe:

arr = np.array([[78, 3412, 98, 3441], [106, 3412, 127, 3434], [139, 3411, 160, 3434], [170, 3411, 191, 3442]])
df = pd.DataFrame(arr, columns=['a', 'b', 'c', 'd'])


The two new columns can now be added as follows:

df['e'] = df['a'] - df['c']
df['f'] = df['a'].diff(1)


Directly using numpy, one possible way would be to do:

arr = np.c_[ arr, arr[:,0] - arr[:,2], np.append(np.NaN, arr[1:, 0] - arr[:-1, 0]) ]

• Thanks. It will help to me – Rajesh das Oct 18 '19 at 13:14
• @Rajeshdas Happy to help :) – Shaido Oct 18 '19 at 15:50