0

This is my code:


import pandas as pd
import re

# reading the csv file
patients = pd.read_csv("partial.csv")
  
# updating the column value/data
for patient in patients.iterrows():
    cip=patient['VALOR_ID']
    new_cip = re.sub('^(\w+|)',r'FIXED_REPLACED_STRING',cip)
    patient['VALOR_ID'] = new_cip
  
# writing into the file
df.to_csv("partial-writer.csv", index=False)
  
print(df)

I'm getting this message:

Traceback (most recent call last): File "/home/jeusdi/projects/workarea/salut/load-testing/load.py", line 28, in cip=patient['VALOR_ID'] TypeError: tuple indices must be integers or slices, not str

EDIT Form code above you can think I need to set a same fixed value to all rows.

I need to loop over "rows" and generate a random string and set it on each different "row".

Code above would be:

for patient in patients.iterrows():
    new_cip = generate_cip()
    patient['VALOR_ID'] = new_cip
1
  • Can you add some data sample to question? Commented Nov 12, 2021 at 9:04

1 Answer 1

2

Use Series.str.replace, but not sure about | in regex. Maybe should be removed it:

df = pd.read_csv("partial.csv")

df['VALOR_ID'] = df['VALOR_ID'].str.replace('^(\w+|)',r'FIXED_REPLACED_STRING')

#if function return scalars
df['VALOR_ID'] = df['VALOR_ID'].apply(generate_cip)

df.to_csv("partial-writer.csv", index=False)
Sign up to request clarification or add additional context in comments.

4 Comments

You can skip the loop, and replace the entire column with that one line, in Pandas?
@ZachYoung - exactly. It was reason add first and last line of code from Q.
I need to generate a random string to be replaced. I mean, I need each "cell value" has a different value after "transformation". Could you provide a way iterating over "rows"? I'm editing post for more details. I'll really appreciate your help.
@Jordi - Can you try df['VALOR_ID'] = df['VALOR_ID'].apply(generate_cip) ?

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.