kovac
kovac

Reputation: 317

How to add a new column (not replace)

import pandas as pd

test=[
      [14,12,1,13,15],
      [11,21,1,19,32],
      [48,16,1,16,12],
      [22,24,1,18,41],
     ]

df = pd.DataFrame(test)
x = [1,2,3,4]
df['new'] = pd.DataFrame(x)

In this example,df will create new column 'new'

What I want is ...

I want create an new DataFrame (df1) include column 'new'(six column), and df is not changed (only five column).

I want df not to change.

How do I do that?

Upvotes: 0

Views: 49

Answers (2)

Marios Nikolaou
Marios Nikolaou

Reputation: 1336

Alternative way, 'e' is new column, np random creates random values for the new column

df.insert(len(df.columns),'e',np.random.randint(0,5,(5,1)))

Upvotes: 0

ALollz
ALollz

Reputation: 59579

You can create the new DataFrame with .assign:

import pandas as pd

df= pd.DataFrame(test)
df1 = df.assign(new=x)

print(df)
    0   1  2   3   4
0  14  12  1  13  15
1  11  21  1  19  32
2  48  16  1  16  12
3  22  24  1  18  41

print(df1)
    0   1  2   3   4  new
0  14  12  1  13  15    1
1  11  21  1  19  32    2
2  48  16  1  16  12    3
3  22  24  1  18  41    4

.assign returns a new object, so you can modify it without affecting the original. The other alternative would be

df1 = df.copy()  #New object, modifications do not affect `df`.
df1['new'] = x

Upvotes: 1

Related Questions