0

I have a dataframe which looks like this,

                     img
0 6479965c_2019_04_15_20_26_25_90.jpg
1 6479965c_2019_04_15_20_26_25_92.jpg
2 6479965c_2019_04_15_20_26_25_93.jpg
3 6479965c_2019_04_15_20_26_25_96.jpg
4 6479965c_2019_04_15_20_26_26_10.jpg
....

How can I replace each value to,

"foo" + str(counter) + ".jpg"

I iterated,

counter = 1
for i in df['img']:
    i = "foo_" + str(counter)  + ".jpg"
    counter += 1

but it does not work.

1
  • It already has .jpg... Commented Apr 16, 2019 at 3:17

2 Answers 2

2

Use the below code, pandas can do:

df['img'] = 'foo_' + (df.index + 1).astype(str) + '.jpg'

And now:

print(df)

Outputs:

            img
0 foo_1.jpg.jpg
1 foo_2.jpg.jpg
2 foo_3.jpg.jpg
3 foo_4.jpg.jpg
4 foo_5.jpg.jpg
Sign up to request clarification or add additional context in comments.

1 Comment

how to get rid of 6479965c_2019_04_15_20_26_25_90 this part ?? I want to have my own counter which starts from 1.
0

Your problem is setting i is not going to change the original value take a look at this example I need to get the index of the current element to set so I'll use enumerate and for efficiency not going to use the constant variable instead add onto the index value

for index, item in enumerate(df['img']):
    df['img'][index] = "foo_" + str(index+1)  + ".jpg

EDIT: Just realized you got a dictionary so you dont have to use enumerate

for index, item in df['img'].items():
    df['img'][index] = "foo_" + str(index+1)  + ".jpg

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.