Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add str to start of each row value

Tags:

python

pandas

I have a pandas dataframe

df = pd.DataFrame({'num_legs': [1, 34, 34, 104 , 6542, 6542 , 48383]})

I want to append a str before each row`s value.

The str is ZZ00000

The catch is that the row data must always = 7 characters in total

so the desired output will be

df =    num_legs
0   ZZ00001
1   ZZ00034
2   ZZ00034
3   ZZ00104
4   ZZ06542
5   ZZ06542
6   ZZ48383

As the column is of type int I was thinking of changing to a str type and then possibly using regex and some str manipulation to achieve my desired outcome..

Is there a more streamlined way possibly using a function with pandas?

like image 619
James Cook Avatar asked Dec 23 '22 16:12

James Cook


1 Answers

Use

df['num_legs'] = "ZZ" + df['num_legs'].astype(str).str.rjust(5, "0")
like image 173
Lambda Avatar answered Jan 05 '23 08:01

Lambda