Reub
Reub

Reputation: 785

pandas dataframe append string to id column

I have a csv file loaded in pandas and I want to append the id with a string

here is my code to do so.

for index_data, row_data in dataset.iterrows():
      dataset.set_value(index_data,'person_id', "u_"+ row_data['person_id'].tostring())

so basically instead of 1,2...n what I want to have is u_1,u_2,u_3 but I keep getting this error

ValueError: invalid literal for long() with base 10: 'u_'

any solution?

Upvotes: 0

Views: 452

Answers (1)

cs95
cs95

Reputation: 403198

The issue is because person_id is an integer column, and set_value would expect a value of the same dtype as the column being mutated. Since you pass a string, the error is thrown (it expected a long, not a string).

Here's the pandaic way of doing it - vectorized string concatenation:

dataset['person_id'] = 'u_' + dataset['person_id'].astype(str)

Upvotes: 1

Related Questions