0

I am looking to change part of the string in a column of a data frame. I, however, can not get it to update in the data frame. This is my code.

import pandas as pd

#File path
csv = '/home/test.csv'

#Read csv to pandas
df = pd.read_csv(nuclei_annotations_csv, header=None, names=['A', 'B', 'C', 'D', 'E', 'F'])

#Select Data to update
paths = df['A']

#Loop over data
for x in paths:
    #Select data to updte
    old = x[:36]
    #Update value
    new = '/Datasets/RetinaNetData'
    #Replace
    new_path = x.replace(old, new)
    #Save values to DataFrame
    paths.update(new_path)

#Print updated DataFrame 
print(df)

The inputs and output I would like are:

Input:

/Annotations/test_folder/10_m03293_ORG.png
/Annotations/test_folder/10_m03293_ORG.png
/Annotations/test_folder/10_m03293_ORG.png
/Annotations/test_folder/10_m03293_ORG.png

OutPut:

/Datasets/RetinaNetData/10_m03293_ORG.png
/Datasets/RetinaNetData/10_m03293_ORG.png
/Datasets/RetinaNetData/10_m03293_ORG.png
/Datasets/RetinaNetData/10_m03293_ORG.png
4
  • So you are trying to replace the first 36 characters in each row of the 'A' column with '/Datasets/RetinaNetData'? Commented Sep 28, 2018 at 15:34
  • can you show us an example of what the data is and what you want to acheive Commented Sep 28, 2018 at 15:35
  • @rahlf23 yes, basically change the directory held in the csv Commented Sep 28, 2018 at 15:37
  • See @ASGM's answer. Commented Sep 28, 2018 at 15:39

1 Answer 1

3

Assuming that all of the rows are strings and all of them have at least 36 characters, you can use .str to get the part of the cells after the 36th character. Then you can just use the + operator to combine the new beginning with the remainder of each cell's contents:

df.A = '/Datasets/RetinaNetData' + df.A.str[36:]

As a general tip, methods like this that operate across the whole dataframe at once are going to be more efficient than looping over each row individually.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.