import pandas as pd
I have a dataframe:
df=pd.DataFrame({'cmplxnumbers':[1+1j,2-2j,3*(1+1j)]})
I need to get the imaginary parts of the numbers in the column.
I do it by:
df.cmplxnumbers.apply(lambda number: number.imag)
I get as a result:
0 1.0
1 -2.0
2 3.0
Name: cmplxnumbers, dtype: float64
Which is as expected.
Is there any quicker, more straightforward method, perhaps not involving the lambda
function?
Pandas DataFrame/Series builds on top of numpy array, so they can be passed to most numpy functions.
In this case, you can try the following, which should be faster than the non-vectorized .apply
:
df['imag'] = np.imag(df.cmplxnumbers)
df['real'] = np.real(df.cmplxnumbers)
Output:
cmplxnumbers imag real
0 1.000000+1.000000j 1.0 1.0
1 2.000000-2.000000j -2.0 2.0
2 3.000000+3.000000j 3.0 3.0
Or you can do agg
:
df[['real','imag']] = df.cmplxnumbers.agg([np.real, np.imag])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With