1

I'm looking to insert a few characters into the beginning of a cell on a CSV using Python. Python needs to do this with the same cell on each row.

As an example, see: Inserting values into specific cells in csv with python

So:

row 1 - cell 3 'Qwerty' - add 3 characters (HAL) to beginning of the cell. So cell now reads 'HALQwerty'

row 2 - cell 3 'Qwerty' - add 3 characters (HAL) to beginning of the cell. So cell now reads 'HALQwerty'

row 3 - cell 3 'Qwerty' - add 3 characters (HAL) to beginning of the cell. So cell now reads 'HALQwerty'

Does anyone know how to do this?

I found this link: https://www.protechtraining.com/blog/post/python-for-beginners-reading-manipulating-csv-files-737

But it doesn't go into enough detail.

1 Answer 1

1

Simplest way is probably to use Pandas. First run 'pip install pandas'

import pandas as pd

# read the CSV file and store into dataframe
df = pd.read_csv("test.csv")

# change value of a single cell directly
# this is selecting index 4 (row index) and then the column name
df.at[4,'column-name'] = 'HALQwerty'

# change multiple values simultaneously 
# here we have a range of rows (0:4) and a couple column values
df.loc[0:4 ,['Num','NAME']] = [100, 'HALQwerty']

# write out the CSV file 
df.to_csv(f"output.csv") 

Pandas allows for a lot of control over your CSV files, and its well documented. https://pandas.pydata.org/docs/index.html

Edit: To allow conditional appending of text:

df = pd.DataFrame({'col1':['a', 'QWERTY', "QWERTY", 'b'], 'col2':['c', 'tortilla', 'giraffe', 'monkey'] })
mask = (df['col1'] == 'QWERTY')
df.loc[mask, 'col1'] = 'HAL' + df['col1'].astype(str)

The mask is the subset of rows that match a condition (where cell value equals "QWERTY"). The ".loc" function identifies where in the dataframe that subset is, and helps to apply whatever change you want.

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

4 Comments

Averroes, this is GREAT help. Thankyou. :)
Any idea how I do the following? Take the string '0875RUNCORN' in a cell Place 'HAL' at the start, so it becomes HAL0875RUNCORN Remove the '0' so it becomes HAL875RUNCORN Repeat this for each row, where the cell in question will be cell 2 in a row.
I have modified my answer to help. I made my own dataframe but it should be simple to apply that code to your own dataframe.
@PaulM the scenario you posted is more complex and not relevant to the original question and would require a different post. I would research "pandas lambda function" to do that.

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.