Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcasting a Series to DataFrame

Tags:

python

pandas

I have a Series like:

A    2
B    3
C    4

And a DataFrame like:

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9

I want to assign the series to all rows in the dataframe. This is the expected output:

    A   B   C
0   2   3   4
1   2   3   4
2   2   3   4

Of cause I can do

for col in ser.index:
    df[col] = ser[col]

but what is a more efficient way?

like image 750
kae_mihara Avatar asked Oct 29 '25 05:10

kae_mihara


1 Answers

Using pandas.DataFrame.div and mul:

df.div(df).mul(s)

Or much faster using numpy.tile (iff df.columns == s.index):

pd.DataFrame(np.tile(s, (len(df), 1)), columns=df.columns)

Output:

     A    B    C
0  2.0  3.0  4.0
1  2.0  3.0  4.0
2  2.0  3.0  4.0
like image 165
Chris Avatar answered Oct 31 '25 08:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!