Home > Mobile >  Python: Appending a row into all rows in a dataframe
Python: Appending a row into all rows in a dataframe

Time:04-18

I have 2 dataframe as shown below

dff = pd.DataFrame([[0.4, 0.2, 0.4], [0.1, 0.3, 0.6], [0.3, 0.2, 0.5], [0.3,0.3,0.4]], columns=['WA', 'WB','WC'])


     WA  WB  WC
0   0.4 0.2 0.4
1   0.1 0.3 0.6
2   0.3 0.2 0.5
3   0.3 0.3 0.4

dff2 = pd.DataFrame([[0.5, 0.2, 0.4]], columns = ['stv_A', 'stv_B', 'stv_c'])
    stv_Astv_Bstv_c
0   0.5 0.2 0.4

Is there anyway to append dff2 which only consist of one row to every single row in ddf? Resulting dataframe should thus have 6 columns and rows

CodePudding user response:

Pandas does the broadcasting for you when you assign a scalar as a column:

import pandas as pd

dff = pd.DataFrame([[0.4, 0.2, 0.4], [0.1, 0.3, 0.6], [0.3, 0.2, 0.5], [0.3,0.3,0.4]], columns=['WA', 'WB','WC'])
dff2 = pd.DataFrame([[0.5, 0.2, 0.4]], columns = ['stv_A', 'stv_B', 'stv_c'])

for col in dff2.columns:
    dff[col] = dff2[col][0] # Pass a scalar

print(dff)

Output:

    WA   WB   WC  stv_A  stv_B  stv_c
0  0.4  0.2  0.4    0.5    0.2    0.4
1  0.1  0.3  0.6    0.5    0.2    0.4
2  0.3  0.2  0.5    0.5    0.2    0.4
3  0.3  0.3  0.4    0.5    0.2    0.4

CodePudding user response:

You can use:

dff[dff2.columns] = dff2.squeeze()
print(dff)

# Output
    WA   WB   WC  stv_A  stv_B  stv_c
0  0.4  0.2  0.4    0.5    0.2    0.4
1  0.1  0.3  0.6    0.5    0.2    0.4
2  0.3  0.2  0.5    0.5    0.2    0.4
3  0.3  0.3  0.4    0.5    0.2    0.4

CodePudding user response:

You can first repeat the row in dff2 len(dff) times with different methods, then concat the repeated dataframe to dff

df = pd.concat([dff, pd.concat([dff2]*len(dff)).reset_index(drop=True)], axis=1)
print(df)

    WA   WB   WC  stv_A  stv_B  stv_c
0  0.4  0.2  0.4    0.5    0.2    0.4
1  0.1  0.3  0.6    0.5    0.2    0.4
2  0.3  0.2  0.5    0.5    0.2    0.4
3  0.3  0.3  0.4    0.5    0.2    0.4
  • Related