0

I want to replace the values in a pandas dataframe column with new values. I know I can assign the array to a new column, drop the original column and then rename the new column as the old column, but that seems like a roundabout way to accomplish such a basic task.

df = pd.DataFrame(np.random.random(10), columns=['Values'])
df['new'] = np.random.random(10)
df.drop(columns = 'Values', inplace = True)
df.rename(columns={"new": "Values"}, inplace=True)

Is there not a better way of accomplishing this?

DanGoodrick
  • 2,818
  • 6
  • 28
  • 52

1 Answers1

1

Simpliest is assign to same column:

df = pd.DataFrame(np.random.random(10), columns=['Values'])
df['Values'] = np.random.random(10)

Or use assign:

df = pd.DataFrame(np.random.random(10),columns=['Values']).assign(Values=np.random.random(10))

print (df)
     Values
0  0.642650
1  0.303899
2  0.395351
3  0.285325
4  0.304549
5  0.820704
6  0.719606
7  0.667412
8  0.545947
9  0.789418
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252