1

I'm having a dataframe and a dictionary based on dictionary values that are present in col1 need to replaced. I tried but it's not changing. What is the efficient way of doing it. Thank You.

df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
di = {1: "A", 2: "B"}

df
  col1 col2
0    w    a
1    A    2
2    B  NaN

Expected output:

df.replace({"col1": di})
  col1 col2
0    w    a
1    1    2
2    2  NaN

2 Answers 2

1

You can create dict with replace key and value with each other then use .replace as your try:

>>> df = pd.DataFrame({'col1': {0: 'w', 1: 'A', 2: 'B'}, 'col2': {0: 'a', 1: 2, 2: np.nan}})
>>> df
    col1    col2
0      w    a
1      A    2
2      B    NaN

>>> di = {1: "A", 2: "B"}
>>> di2 = {v:k for k,v in di.items()}
>>> df.replace({"col1": di2})
    col1    col2
0      w    a
1      1    2
2      2    NaN
Sign up to request clarification or add additional context in comments.

Comments

1

I'd probably just iterate over the dictionary pairs like this:

for k, v in di.items()
     df['col1'].replace(k, v, inplace=True)

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.