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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With