Home > Blockchain >  How to edit data in a CSV file?
How to edit data in a CSV file?

Time:10-29

I'm trying to change someone's name in a Pandas data frame.

I've tried using this code, but it just adds to the current name:

def rename(self):
    id = '1'
    person = (df.loc[df['id'] == id])
    print(person)
    newName = 'tom'
    df.loc[df['id'] == id, ['name']] = df['name'] - df['name']   newName

Input:

id  name  age
1   bob   40

Expected output:

id  name  age
1   tom   40

CodePudding user response:

Hi this is an if statement in pandas you can use either:

df.loc[df.id == 1, 'name'] = 'tom'

or,

df.loc[df.name == 'bob', 'name'] = 'tom'

or,

df.loc[(df.id == 1) & (df.name == 'bob'), 'name'] = 'tom'

you can also try to make a dictionary:

name_change = {'old_name':'new_name'}
df['name'] = df.name.replace(name_change)

CodePudding user response:

def rename(self):
    id = '1'
    person = df[df['id'] == id]
    newName = 'tom'
    df[df['id'] == id].name = newName
  • Related