Skip to content Skip to sidebar Skip to footer

Combining Real And Imag Columns In Dataframe Into Complex Number To Obtain Magnitude Using Np.abs

I have a data frame that has complex numbers split into a real and an imaginary column. I want to add a column (2, actually, one for each channel) to the dataframe that computes t

Solution 1:

You can do simple multiplication with 1j which denotes the complex number 0+1j, see imaginary literals:

df['ch1_log_mag'] = 20 * np.log10((df.ch1_real + 1j * df.ch1_imag).abs())

complex(df.ch1_real, df.ch1_imag) doesn't work as it needs a float argument, not a whole series. df.loc[0,df['ch1_real']] is not a valid expression, as the second argument must be a string, not a series (df.loc[79,'ch1_real'] would work for accessing an element). If you want to use apply it should be 20 * np.log10(df.apply(lambda x: complex(x.ch1_real, x.ch1_imag), 1).abs()) but as apply is just a disguised loop over the rows of the dataframe it's not recommended performancewise.

There's no difference between df.ch1_real and df['ch1_real'], it's a matter of personal preference. If your column name contains spaces or dots or the like you must use the latter form however.

Post a Comment for "Combining Real And Imag Columns In Dataframe Into Complex Number To Obtain Magnitude Using Np.abs"