join() returning NaN values in python

Viewed 307

I have some int type values in my series and I tried to join it with a data frame but the series got added as a column but the values are not as expected they are filled with 'NaN' this is my code

s3=Series(np.arange(6))
s3.name="added_series"
np.random.seed(25)
df=DataFrame(np.random.rand(36).reshape((6,6)),index=['r1','r2','r3','r4','r5','r6'])
dfadd=DataFrame.join(df,s3)

Here is the output image

2 Answers

If you just want to add a new column, you don't have to use join().

new_df = df
new_df['added_series'] = list(s3)

Output :

Out[54]:
0   1   2   3   4   5   added_series
r1  0.870124    0.582277    0.278839    0.185911    0.411100    0.117376    0
r2  0.684969    0.437611    0.556229    0.367080    0.402366    0.113041    1
r3  0.447031    0.585445    0.161985    0.520719    0.326051    0.699186    2
r4  0.366395    0.836375    0.481343    0.516502    0.383048    0.997541    3
r5  0.514244    0.559053    0.034450    0.719930    0.421004    0.436935    4
r6  0.281701    0.900274    0.669612    0.456069    0.289804    0.525819    5
import pandas as pd

pd.concat([df.reset_index(), DataFrame(s3)], axis=1).set_index("index")

or using:

df.reset_index().join(DataFrame(s3), how="inner").set_index("index")

the output is:

Out[29]: 
              0         1         2         3         4         5  added_series
index                                                                          
r1     0.870124  0.582277  0.278839  0.185911  0.411100  0.117376             0
r2     0.684969  0.437611  0.556229  0.367080  0.402366  0.113041             1
r3     0.447031  0.585445  0.161985  0.520719  0.326051  0.699186             2
r4     0.366395  0.836375  0.481343  0.516502  0.383048  0.997541             3
r5     0.514244  0.559053  0.034450  0.719930  0.421004  0.436935             4
r6     0.281701  0.900274  0.669612  0.456069  0.289804  0.525819             5
Related