Home > Software engineering >  Making two dictionaries from a pandas dataframe
Making two dictionaries from a pandas dataframe

Time:07-25

df = pd.DataFrame({'A':['a_o','a','b_o','b','c'],'B':[1,0,1,1,0],'C':[99,24,67,89,91]})

For the above dataframe df, I want to make two dictionary as below:

 dict1 = {'a_o':99,'b_o':67}
 dict2 = {'a':0,'b':1,''c':0}

What I want to do is, for all entries ending with '_o' in column 'A', I want to make a dictionary dict1 and map its keys to corresponding value of column 'C'. For all other entries in column 'A', I want to make a dictionary dict2 and map its keys to corresponding value of column 'B'.

How can I do that? I was trying to make two dataframes,one for those rows whose entries in column 'A' ends with '_o', other dataframe for the rest rows. If I achieve this I'll be able to make dict1 and dict2 using dict(zip(____)). But I couldn't make dataframes. Please help.

CodePudding user response:

Try:

m = df.A.str.endswith("_o")
dict1 = dict(zip(df.loc[m, "A"], df.loc[m, "C"]))
dict2 = dict(zip(df.loc[~m, "A"], df.loc[~m, "B"]))

print(dict1)
print(dict2)

Prints:

{'a_o': 99, 'b_o': 67}
{'a': 0, 'b': 1, 'c': 0}
  • Related