Changing data in CSV cells with Python

Viewed 36

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 Answers

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.

Related