2

I would like to know how I can change the values of a column dynamically as I grab the information from a web scrape.

Currently, I have something like this:

number name 12 NA 13 NA 14 NA 15 NA

and I would like to receive something like this:

number name 12 Mike 13 Bob 14 Bobby 15 Mark

I have tried using this: for number in phone_book: name = get_name() phonebook['names'][number] = name

and

phonebook.loc[phonebook.index[number], 'name'] = name

but it just sets the name of the last number for all:

number name 12 Mark 13 Mark 14 Mark 15 Mark How could I get it to add each name to its respective number?

Thanks

3
  • phonebook.loc[phonebook.number == number, 'names'] = name Commented Nov 12, 2019 at 18:12
  • @QuangHoang Thank you so much, that works! Can you explain why I need the phonebook.number == number? Commented Nov 12, 2019 at 18:31
  • phonebook.number == number looks through the 'number' columns in your phonebook and mark the correct ones. .loc gives you access to the corresponding rows/columns. Commented Nov 12, 2019 at 18:32

2 Answers 2

2

From your web scrape you could build a dict that looks like this:


name = {12: 'Mike', 13: 'Bob', 14: 'Bobby', 15: 'Mark'}

Then you can map to your existing frame:

df['name']=df['number'].map(name)
df = df.set_index('number')
print(df) 
         
number   name    
12       Mike
13        Bob
14      Bobby
15       Mark
Sign up to request clarification or add additional context in comments.

Comments

0

You have several way to do it, first like @Quang Hoang comment :

phonebook.loc[phonebook.number == number, 'names'] = name

You can also do like this :

for number in phone_book:
    name = get_name()
    phonebook[phonebook["number"] == number] = name

or like this :

names = []
for number in phone_book:
    names.append(get_name())
phonebook["name"] = names

Note that the prefered method is the first one.

Comments

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.