Skip to content Skip to sidebar Skip to footer

Divide A Dataframe By Another Dataframe According To Index

I am trying to divide rows of a dataframe by the same index row in another dataframe. There are the same amount of columns in each dataframe. The goal is to divide a list of column

Solution 1:

divide by values to get around index alignment

dfd = df1.div(df2.values)
dfd.columns = df1.columns + '/' + df2.columns

dfd

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2

Or

c = df1.columns + '/' + df2.columns
pd.DataFrame(df1.values / df2.values, df1.index, c)

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2

rebirth of @ScottBoston's answer

c = df1.columns + '/' + df2.columns
d1 = dict(zip(df1.columns, c))
d2 = dict(zip(df2.columns, c))
df1.rename(columns=d1) / df2.rename(columns=d2)

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2
4   NaN  NaN  NaN

Solution 2:

Using align to force index alignment:

df3 = np.divide(*df1.align(df2, axis=0))
df3.columns = df1.columns + '/' + df2.columns

The resulting output:

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2
4   NaN  NaN  NaN

Solution 3:

Pandas does intrinsic data alignment, so if you label your row index and column the same in both datafames, Pandas will perform the operation as expected.

You need rename your columns to a common name with dictionary mapping old column name to new name as follows:

rn_df1 = dict(list(zip(df1.columns.values,(df1.columns+'/'+df2.columns))))
rn_df2 = dict(list(zip(df2.columns.values,(df1.columns+'/'+df2.columns))))
df1.rename(columns=rn_df1).div(df2.rename(columns=rn_df2))

output:

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2

Post a Comment for "Divide A Dataframe By Another Dataframe According To Index"