1

I have a pandas dataframe with a column that is a small selection of strings. Let's call the column 'A' and all of the values in it are string_1, string_2, string_3.

Now, I want to add another column and fill it with numeric values that correspond to the strings.

I created a dictionary

d = { 'string_1' : 1, 'string_2' : 2, 'string_3': 3}

I then initialized the new column:

df['B'] = pd.Series(index=df.index)

Now, I want to fill it with the integer values. I can call the values associated with the strings in the dictionary by:

for s in df['A']:
   n = d[s]

That works fine, but I've tried using just plain df['B'] = n to fill the new column in the for-loop, but that doesn't work, and I've tried to figure out indexing with pandas.

2 Answers 2

1

If I understand you correctly you can just call map:

df['B'] = df['A'].map(d)

This will perform the lookup and fill the values you are looking for.

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

Comments

0

Rather than fill as an empty column, you can simply populate this with an apply:

df['B'] = df['A'].apply(d.get)

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.