Assume the following dataframes:
df1:
a
10.
20.
30.
40.
50.
60.
70.
80.
90.
100.
110.
120.
df2:
b
1.
2.
df3:
b
1.
2.
3.
Knowing len(df1.values) % len(df2.values) == 0, I want to divide each element of df1 by each element of df2, after having repeated df2 as many times as needed to fit df11's length, meaning in this case
result(df1, df2):
a
10.
10.
30.
20.
50.
30.
70.
40.
90.
50.
110.
60.
result(df1, df3):
a
10.
10.
10.
40.
25.
20.
70.
40.
30.
100.
55.
40.
What is the cleanest way to achieve this, preferably without going through numpy?
Here's one way using np.resize, where the new array will be filled with copies of the original until it fits the specified length:
df1['a'] /= np.resize(df2.b.values, df1.shape[0])
a
0 10.0
1 10.0
2 30.0
3 20.0
4 50.0
5 30.0
6 70.0
7 40.0
8 90.0
9 50.0
10 110.0
11 60.0
Or using pd.np.tile:
df1['a'] /= pd.np.tile(df2.b, df1.shape[0]//df2.shape[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