Home > other >  How to iterate and filter a dataframe using dictionary in python?
How to iterate and filter a dataframe using dictionary in python?

Time:09-26

I have a pandas dataframe and a dictionary:

enter image description here

dict = {'a_w':5,'c_y':8}

I want to filter some records in the dataframe using the dictionary and add the dictionary value as a new column to the dataframe.

enter image description here

I tried to loop over the dataframe and use it for filtering the dataframe but it did not work.

for i in df['Col1']:
    for j in df['Col2']:
        if i "_" j in dict.keys():
            df['Col3']= dict.values()

How to solve the issue?

Thanks.

CodePudding user response:

Try:

dct = {"a_w": 5, "c_y": 8}

df["col3"] = (df["col1"]   "_"   df["col2"]).map(dct).fillna("")
print(df)

Prints:

  col1 col2 col3
0    a    w  5.0
1    b    x     
2    c    y  8.0
3    d    z     

CodePudding user response:

try this:

newcol = []
for i in range(len(df)):
  if df.loc[i, "col1"]   "_"   df.loc[i, "col2"] in dict:
    newcol.append(dict[df.loc[i, "col1"]   "_"   df.loc[i, "col2"]])
  else:
    newcol.append("")
df["col3"] = newcol
  • Related