Home > database >  pandas "map" the truth value of a dataframe is ambiguous
pandas "map" the truth value of a dataframe is ambiguous

Time:10-05

I'm having this resultsdf in Panda

     Antecedent Consequent  confidence       lift  support
0       (3623,)    (2568,)    0.829517  13.964925   0.0326
1       (4304,)    (4305,)    0.808362  24.348264   0.0232
2  (3623, 3970)    (2568,)    0.922581  15.531661   0.0286

and dictionary df

        key                                 name
0     1001                 Boombox Ipod Classic
1     1002               USB Office Mirror Ball

I was trying to interpret Antecedent with dictionary by adding

resultsdf['Antecedent_name'] = resultsdf['Antecedent'].astype(str).map(df)

I'm getting error

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), `a.item(), a.any() or a.all().`

CodePudding user response:

Seems to me that you are trying to pass a df to map. you should pass a dict.

Try this:

resultsdf['Antecedent_name'] = resultsdf['Antecedent'].astype(str).map(df.to_dict())

I'm not sure if the to_dict() default output is enough. You can check the parameter to change the output formats here

Update:

Considering df1 your main df and df2 you key:name df, you can do something like this:

def check(x):
  lst = []
  for elem in x:
      if elem in df2.to_dict("list")["key"]:
          lst.append(df2.to_dict("list")["name"][df2.to_dict("list")["key"].index(elem)])
return tuple(lst)

 df1['Antecedent_name'] = df1['Antecedent'].map(check)

It's not that beautiful, but I think that works. Maybe instead of a lambda you can just create a separated function and

CodePudding user response:

thank you everyone

resultsdf['Antecedent_name'] = resultsdf.Antecedent.map(lambda a: [df[int(id)] for id in a] )
  • Related