1
$\begingroup$

I have 2 dataframes: df1 = pd.DataFrame({"animal": [Cat, Dog, Rat, Bull, Dog, Bull, Bull, Dog, Cat, Rat, Dog], "lifeSpan": [2, 4, 6, 0, 4, 0, 0, 4, 2, 6, 4]})

df2 = pd.Dataframe({"animal":[Bull, Cat, Rat, Dog]}) The "LifeSpan" value is unique to each i in df1["animal"]. I need a third dataframe that mentions the "lifeSpan" value in a separate column against each j in df2["animal"] based on the 'lifespan' values in df1.

$\endgroup$
0
$\begingroup$

Just use pandas.merge to combine the two dataframes:

import pandas as pd

df1 = pd.DataFrame({"animal": ["Cat", "Dog", "Rat", "Bull", "Dog", "Bull", "Bull", "Dog", "Cat", "Rat", "Dog"], "lifeSpan": [2, 4, 6, 0, 4, 0, 0, 4, 2, 6, 4]})
df2 = pd.DataFrame({"animal":["Bull", "Cat", "Rat", "Dog"]})

df3 = df2.merge(df1.drop_duplicates(), on="animal")

This returns the following dataframe:

animal lifeSpan
Bull 0
Cat 2
Rat 6
Dog 4
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.