I have following dataframe :
state city alt_city FL FT. PIERCE FORT PIERCE FL FT. PIERCE FORTPIERCE FL FT. PIERCE FT.PIERCE FL FORT PIERCE FORTPIERCE FL FORT PIERCE FT PIERCE FL FORT PIERCE FT. PIERCE FL FORT PIERCE FT.PIERCE FL FORT PIERCE FTPIERCE AK ANCHORAGE ANCH AK ANCHORAGE ANCHORAGE and I want to genearte a dictionary from it based on certain conditions:
Following is a pseudo code :
def map_df_to_dict(d,state,city,alt_city): key1 = (state,city) val1 = alt_city key2 = (state,alt_city) val2 = city if key1 in d: d[key1].append(val1) else: d[key1] = [] d[key1].append(val1) if key2 in d: d[key2].append(val2) else: d[key2] = [] d[key2].append(val2) return d If I apply it on dataframe using following code :
cs_d = {} cs_dict = df.apply(lambda x: map_df_to_dict(cs_d,x['state'],x['city'],x['alt_city']), axis=1) then it will return dictionary for every row in the dataframe.
But how can I apply this on a dataframe so that it will not return weird results.