'merge' 2 dataframes on elements from list?

前端 未结 4 1293
刺人心
刺人心 2021-01-23 06:20

I want to do the following merge (hard to describe in words): This are my Dataframes

df8=pd.DataFrame({\'names\':[[\'Hans\',\'Meier\'],[\'Debby\',\'Harry\',\'Pet         


        
4条回答
  •  灰色年华
    2021-01-23 07:02

    df8['content']= df8['names'].apply(lambda x: [df9.loc[name,'text'][0] for name in x])

    This return an error if there is a name that isn't found in df9. You can make it more robust with

    df8['content']= df8['names'].apply(lambda x: [df9['text'].get(name)[0] if df9['text'].get(name) else None for name in x])

    This will have a list that contains the text for every name found, and None for any name not found.

    If all you're using df9 for is as a look-up table, then it would be more appropriate to store it as a dictionary, in which case it would be

    df8['content']= df8['names'].apply(lambda x: [my_dict.get(name)[0] if my_dict.get(name) else None for name in x])

提交回复
热议问题