till Kadabra
till Kadabra

Reputation: 488

Pandas: replace column in dataframe by range function

There is a Unique Key Column in my csv file and it has in every row the value 1. I want to replace them by real unique values (1,2,3,4,5 ....).

I try:

data=pd.read_csv(csv_file)
data['Unique Key'] = data['Unique Key'].replace(1:range(1))

but obviously doesn't work ;(

Upvotes: 1

Views: 991

Answers (3)

BENY
BENY

Reputation: 323326

May using reset_index()

data['Unique Key'] = data.reset_index().index+1

Upvotes: 2

ALollz
ALollz

Reputation: 59579

Since it's a column of 1s

df['Unique Key'] = df['Unique Key'].cumsum()

Upvotes: 3

Rocky Li
Rocky Li

Reputation: 5958

data['Unique Key'] = np.arange(len(data))

each column in the pd.DataFrame can be replaced/ created by a numpy array of the same length.

If you want the keys to start from 1, you can do

data['Unique Key'] = np.arange(len(data)) + 1

Upvotes: 5

Related Questions