Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a dataframe containing complex numbers from dataframes with real numbers in python?

In python, I have a dataframe with 2 columns of real numbers. I want to make complex number and use those two columns as real and imaginary parts of my new set of data. I have tried complex(df['wspd'].astype(float),df['wdir'].astype(float)) but I still get this error:

cannot convert the series to <class 'float'>

How can I make it happen?

like image 825
Anthony Avatar asked Apr 20 '26 06:04

Anthony


1 Answers

The function complex can handle only scalars. You can convert the second column to imaginary multiplying by 1j, then sum:

df['wspd'] + df['wdir'] * 1j

Sample:

df = pd.DataFrame({'wspd':[10.23,2.4,30.6], 'wdir':[2.3,7.8,4]})
df['com'] = df['wspd'] + df['wdir'] * 1j
print (df)
    wspd  wdir           com
0  10.23   2.3  (10.23+2.3j)
1   2.40   7.8    (2.4+7.8j)
2  30.60   4.0     (30.6+4j)
like image 171
Stop harming Monica Avatar answered Apr 21 '26 21:04

Stop harming Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!