1
$\begingroup$

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']
]
$\endgroup$
0
$\begingroup$

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]) ] 
$\endgroup$
  • $\begingroup$ Thanks. It will help to me $\endgroup$ – Rajesh das Oct 18 at 13:14
  • $\begingroup$ @Rajeshdas Happy to help :) $\endgroup$ – Shaido - Reinstate Monica Oct 18 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.