1

Need help in filling 0's.

In the below dataframe i have a column "Item_Visibility" which has zeros. I need to fill those with values from second dataframe(image 2). The common column between the 2 dataframes is "Item_Identifier".

Thanks in advance

enter image description here enter image description here

Amit
  • 6,839
  • 21
  • 56
  • 90

2 Answers2

3

try this:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A":["a", "b", "c", "d", "e"], "B":[1, 2, 0, 0, 0]})
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])

mask = df["B"] == 0
df.loc[mask, "B"] = s[df.loc[mask, "A"]].values

df:

   A  B
0  a  1
1  b  2
2  c  0
3  d  0
4  e  0

s:

a    10
b    20
c    30
d    40
dtype: int64

output:

   A     B
0  a   1.0
1  b   2.0
2  c  30.0
3  d  40.0
4  e   NaN
HYRY
  • 94,853
  • 25
  • 187
  • 187
1

I think you can use mask with maping by Series by map:

print (df1)
       a      b        c      d
0  FDA15   9.30  Low Fat  0.016
1  FDX07  19.20  Regular  0.000
2  NCD19   8.93  Low Fat  0.000
3  FDP10    NaN  Low Fat  0.127

print (df2)
       e       d
0  FDW59  0.0202
1  FDX07  0.0178

df1.d = df1.d.mask(df1.d == 0, df1.a.map(df2.set_index('e')['d']))
print (df1)
       a      b        c       d
0  FDA15   9.30  Low Fat  0.0160
1  FDX07  19.20  Regular  0.0178
2  NCD19   8.93  Low Fat     NaN
3  FDP10    NaN  Low Fat  0.1270
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252