Function on column from dictionary

Viewed 52

I have a df like this:

df = pd.DataFrame({'A': [3, 1, 2, 3],
                    'B': [5, 6, 7, 8]})

    A   B
0   3   5
1   1   6
2   2   7
3   3   8

And I have a dictionary like this:

{'A': 1, 'B': 2}

Is there a simple way to performa function (eg. divide) on df values based on the values from the dictionary?

Example, all values in column A is divided by 1, and all values in column B is divided by 2?

2 Answers

For me working division by dictionary, because keys of dict matching columns names:

d = {'A': 1, 'B': 2}
df1 = df.div(d)   

Or:

df1 = df / d

print(df1)
     A    B
0  3.0  2.5
1  1.0  3.0
2  2.0  3.5
3  3.0  4.0

If you want to do it using for loop you can try this

df = pd.DataFrame({'A': [3, 1,2, 3, 4],
                    'B': [5, 6, 7, 8, 9]})
dict={'A': 1, 'B': 2}

final_dict={}
for col in df.columns:
  if col in dict.keys():
    for item in dict.keys():
      if col==item:
        lists=[i/dict[item] for i in df[col]]
        final_dict[col]=lists

df=pd.DataFrame(final_dict)
Related