Zanam
Zanam

Reputation: 4807

Append and fill row dataframe to a larger dataframe to create new columns

I have a larger dataframe as follows:

df1

Month      Bkt    Cion
2021-06-01 Ofk    0.07
2021-06-01 Ofk    0.23
2021-06-01 Onk    0.10
2021-06-01 Onk    0.00

I have another very large single row dataframe as:

row.to_frame().T
        S1   S2
1       13   65

I want to append row to df1 to get the following:

Month      Bkt    Cion   S1   S2
2021-06-01 Ofk    0.07   13   65
2021-06-01 Ofk    0.23   13   65
2021-06-01 Onk    0.10   13   65
2021-06-01 Onk    0.00   13   65

I am not sure how to approach the above?

Upvotes: 1

Views: 103

Answers (1)

Henry Ecker
Henry Ecker

Reputation: 35676

One option would be to scale df2 with Index.repeat + loc to the same length as df1:

df1[df2.columns] = df2.loc[df2.index.repeat(len(df1))].values

df1:

        Month  Bkt  Cion  S1  S2
0  2021-06-01  Ofk  0.07  13  65
1  2021-06-01  Ofk  0.23  13  65
2  2021-06-01  Onk  0.10  13  65
3  2021-06-01  Onk  0.00  13  65

Another option with concat + ffill on the df2 columns:

new_df = pd.concat((df1, df2), axis=1)
new_df[df2.columns] = new_df[df2.columns].ffill()

new_df:

        Month  Bkt  Cion    S1    S2
0  2021-06-01  Ofk  0.07  13.0  65.0
1  2021-06-01  Ofk  0.23  13.0  65.0
2  2021-06-01  Onk  0.10  13.0  65.0
3  2021-06-01  Onk  0.00  13.0  65.0

Frames Used:

df1 = pd.DataFrame({
    'Month': ['2021-06-01', '2021-06-01', '2021-06-01', '2021-06-01'],
    'Bkt': ['Ofk', 'Ofk', 'Onk', 'Onk'],
    'Cion': [0.07, 0.23, 0.1, 0.0]
})

df2 = pd.DataFrame({'S1': [13], 'S2': [65]})

Upvotes: 1

Related Questions