scott martin
scott martin

Reputation: 1293

Pandas - Filling each rows of one Dataframe with value from another Dataframe

I have two Dataframes one with set of dates (df1) and another with set of emp_ids (df2). I am trying to create a new Dataframe such that every emp_id in df2 is tagged to every date in df1.

Given below is how my Dataframe look like

df1

2018-01-01
2018-01-02
2018-01-03
2018-01-04

df2

emp_1
emp_2
emp_3

Expected output:

2018-01-01,emp_1
2018-01-02,emp_1
2018-01-03,emp_1
2018-01-04,emp_1
2018-01-01,emp_2
2018-01-02,emp_2
2018-01-03,emp_2
2018-01-04,emp_2
2018-01-01,emp_3
2018-01-02,emp_3
2018-01-03,emp_3
2018-01-04,emp_3

I converted the date column to a string and tried doing the below but it returned an empty Dataframe

I tried doing pd.merge(df1, df2])

Upvotes: 0

Views: 82

Answers (1)

Etienne Herlaut
Etienne Herlaut

Reputation: 586

What you're trying to do is called carthesian product. In pandas you can do it that way:

df1['key'] = 0
df2['key'] = 0

result = df1.merge(df2, how='outer').drop('key',axis= 1)

Edit : to proove it works

df1 = pd.DataFrame(['2018-01-01','2018-01-02','2018-01-03','2018-01-04'],columns=['date'])
df2 = pd.DataFrame(['emp_1','emp_2','emp_3'],columns=['id'])

# res
df1['key'] = 0
df2['key'] = 0

res = df1.merge(df2, how='outer').drop('key',axis= 1)

# print
print(res.sort_values('id'))

Console :

    date        id
0   2018-01-01  emp_1
3   2018-01-02  emp_1
6   2018-01-03  emp_1
9   2018-01-04  emp_1
1   2018-01-01  emp_2
4   2018-01-02  emp_2
7   2018-01-03  emp_2
10  2018-01-04  emp_2
2   2018-01-01  emp_3
5   2018-01-02  emp_3
8   2018-01-03  emp_3
11  2018-01-04  emp_3

Upvotes: 2

Related Questions