Can you duplicate rows in a pandas dataframe based on how many times a feature value appears in another dataframe?

Viewed 137

So I have two pandas dataframes. One is a list of names and values (each name occurs once):

Names Values
a 0
b 10
c 0
d 10
e 0
f 10

The second just has the same name values as the first dataframe, but each name can occur multiple or 0 times and in a random order.

Names
a
b
c
c
f

Is there a way I could duplicate and remove rows from the first data set, so each name occurs the same number of times in the first dataset as the name occurs in the second dataset. for Example:

Names Values
a 0
b 10
c 0
c 0
f 10

BTW all the names are in alphabetical order.

The only way I can think of doing this is making a numpy array out of the names column of the second dataframe, then looping through that array, getting the row of the first dataframe where the names column equals the value of the array at each index, and adding that row to a new dataframe.

But that seems like it would take a long time and I have pretty big dataset(50k rows) so If anybody has a faster suggestion, it would be much appreciated.

1 Answers
df2.merge(df1, on="Names")

Output

    Names   Values
0   a       0
1   b       10
2   c       0
3   c       0
4   f       10

Explanation We can merge df2 and df1 as left or inner join. We have used default inner join in above solution.

Related