Home > Net >  How to replace pandas dataframe column values based on dictionary key and values?
How to replace pandas dataframe column values based on dictionary key and values?

Time:10-28

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

CodePudding user response:

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

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

CodePudding user response:

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
  • Related