I have a dataframe, and I am trying to find the numeric difference between different rows within one column (series), resulting in a square matrix with both dimensions equal to the length of the dataframe.
import pandas as pd
import numpy as np
df = pd.DataFrame([[200, 2],[100,2], [1000,10], [600,5], [50,1]],
columns=['Sales','Total prods'])
print(df['Sales'])
0 200
1 100
2 1000
3 600
4 50
Name: Sales, dtype: int64
I have written this function:
def numerical_scoring(col_name, result_ints):
matrix_df = np.zeros(shape=(len(result_ints), len(result_ints)))
for index_x, row_x in result_ints[[col_name]].iterrows():
for index_y, row_y in result_ints[[col_name]].iterrows():
if index_x == index_y:
matrix_df[index_x, index_y] = 1
else:
matrix_df[index_x, index_y] = abs(row_x[0] - row_y[0])
return matrix_df
print(numerical_scoring('Sales', df))
[[ 1. 100. 800. 400. 150.]
[100. 1. 900. 500. 50.]
[800. 900. 1. 400. 950.]
[400. 500. 400. 1. 550.]
[150. 50. 950. 550. 1.]]
This code works for small dataframes, but when the dataframe grows to millions of records, this is taking a long time to complete. Is there a more efficient way of transforming the data?