Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

I have the following indexed DataFrame with named columns and rows not- continuous numbers:

   a        b        c         d 

2 0.671399 0.101208 -0.181532  0.241273

3 0.446172 -0.243316 0.051767  1.577318 

5 0.614758 0.075793 -0.451460  -0.012493

I would like to add a new column, 'e', to the existing data frame and do not want to change anything in the data frame (i.e., the new column always has the same length as the DataFrame).

0 -0.335485 

1 -1.166658 

2 -0.385571 

dtype: float64

I tried different versions of join, append, merge, but I did not get the result I wanted, only errors at most. How can I add column e to the above example?

1 Answer

0 votes
by (106k points)
edited by

The best method to use would be to add the values of a Series as a new column of a DataFrame could be using  assign()below is the piece of code that illustrated the use of it:

df1 = df1.assign(e=p.Series(np.random.randn(sLength)).values)

Another way to get the extra column would be to use the series() method with this code.

sLength = len(df1['a']

df1 

df1['e'] = p.Series(np.random.randn(sLength),index=df1.index) 

df1 

To know more about this you can have a look at the following video tutorial:-

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...