user6882757
user6882757

Reputation:

How to add two column in pandas

Below is the data frame df

Id,real, imaginary
1,30,7
2,40,-8
3,50,-6

psudeo code df['z'] = df.apply(lamda x: x['real'] + x['imaginary']* i)

Expected Out df['z']

30 + 7i
40 - 8i
50 - 6i

Upvotes: 1

Views: 46

Answers (2)

Mostafa
Mostafa

Reputation: 16

df['z'] = [complex(*e) for e in zip(df.real, df.imag)]

result:

real  imag                    z
30     7  30.000000+7.000000j
40    -8  40.000000-8.000000j
50    -6  50.000000-6.000000j

How to remove the 0000?

convert the data type of pandas to native python types as follows:

d = df.astype(object)

result:

In [60]: df
Out[60]:
   real  imag                    z
0    30     7  30.000000+7.000000j
1    40    -8  40.000000-8.000000j
2    50    -6  50.000000-6.000000j

In [61]: d = df.astype(object)

In [62]:

In [62]: d
Out[62]:
  real imag        z
0   30    7  (30+7j)
1   40   -8  (40-8j)
2   50   -6  (50-6j)

Upvotes: 0

BENY
BENY

Reputation: 323326

Is this complex number ?

df['real'] + df['imaginary'] * 1j
0    30.000000+7.000000j
1    40.000000-8.000000j
2    50.000000-6.000000j
dtype: complex128

Upvotes: 1

Related Questions