Add column 0 value to different column and add text to that cell

Viewed 31

I have a csv file with several rows and columns. Sometimes the text "markers" appears in the file and sometimes it doesn't. I need a code that will replace that "markers" text with the first row's value plus an additional string. The code below shows what I am trying to do but it doesn't quite work the way I'd hoped it would. I'm sure pandas can do it, but I'm not as familiar.

   import csv
   with open(os.getcwd()+f'\\DeleteMe.csv', 'r') as f1:
       input = f1.read()
       for row in input:
           input=input.replace('markers', row[0] + ' text')
       with open(os.getcwd()+f'\\Final.csv', "w") as f1:
           f1.write(input)

Example CSV input(No headers):

title1 1 2 markers 3 4
title2 1 2
title3 1 2 markers 3 4

Example CSV Output (what I'm trying to do):

title1 1 2 title1 text 3 4
title2 1 2
title3 1 2 title3 text 3 4

It's ok that there are blanks at this stage. Just need the title added to the column where "markers" appears. My program cleans up the blanks later so the csv is nice and neat.

Using Python 3 on windows

Thanks in advance

1 Answers

You could try this:

import pandas as pd

# Toy dataframe
df = pd.DataFrame(
    {
        "0": [
            "title1",
            "title2",
            "title3",
        ],
        "1": [1, 1, 1],
        "2": [2, 2, 2],
        "3": ["markers", "", "markers"],
        "4": [3, "", 3],
        "5": [4, "", 4],
    }
)

# Filter df
df.loc[df["3"] == "markers", "3"] = df.loc[df["3"] == "markers", "0"]

# Add new values
df["3"] = pd.Series([f"{value} text" if value else "" for value in df["3"].values])

print(df)
# Outputs
        0  1  2            3  4  5
0  title1  1  2  title1 text  3  4
1  title2  1  2
2  title3  1  2  title3 text  3  4
Related