Elliott Davey
Elliott Davey

Reputation: 67

How do I add repeated month rows for every unique value in a pandas dataframe column?

I have a data frame that looks like the following:

df1 = pd.DataFrame({'Part':['Wheel', 'Door', 'Light', 'Seatbelt']})

enter image description here

I want to add month columns for each unique value of 'part' so that I then get a dataframe that looks like so:

df2 = pd.DataFrame({'Part':['Wheel','Wheel','Wheel','Wheel','Wheel','Wheel','Wheel','Wheel'
                        ,'Door','Door','Door','Door','Door','Door','Door','Door'
                        ,'Light','Light','Light','Light','Light','Light','Light','Light'
                       ,'Seatbelt', 'Seatbelt','Seatbelt','Seatbelt','Seatbelt','Seatbelt','Seatbelt','Seatbelt',]
               ,'Month':['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
                        'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
                        'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
                        'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',]})

enter image description here

Is there a function in pandas python that will allow me to add these rows for every unique value?

The main idea is that once I have created this dataframe I can then merge another dataframe to this one, so that where there are values for zero they show once merged.

Upvotes: 3

Views: 512

Answers (1)

jezrael
jezrael

Reputation: 863116

Use itertools.product with list of months passed to DataFrame constructor:

from  itertools import product

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August']
df = pd.DataFrame(product(df1['Part'].unique(), months), columns=['Part','Month'])

print (df)
        Part     Month
0      Wheel   January
1      Wheel  February
2      Wheel     March
3      Wheel     April
4      Wheel       May
5      Wheel      June
6      Wheel      July
7      Wheel    August
8       Door   January
9       Door  February
10      Door     March
11      Door     April
12      Door       May
13      Door      June
14      Door      July
15      Door    August
16     Light   January
17     Light  February
18     Light     March
19     Light     April
20     Light       May
21     Light      June
22     Light      July
23     Light    August
24  Seatbelt   January
25  Seatbelt  February
26  Seatbelt     March
27  Seatbelt     April
28  Seatbelt       May
29  Seatbelt      June
30  Seatbelt      July
31  Seatbelt    August

Upvotes: 2

Related Questions