Results of a function in a DataFrame in python

2

I have a function in python that uses values from two columns labeled as 'POSITION_X' and 'POSITION_Y' in a .csv file (df1)

The function calculates the sum |Xn-Xn+N|+|Yn-Yn+N| where n is the row number and N is the separation between the rows.

The code looks like this:

df1 = df[['TRACK_ID','POSITION_X','POSITION_Y','POSITION_T']].copy

def radial(df1, coords=['POSITION_X', 'POSITION_Y']): 
        tau = t.copy()
        shifts = np.floor(tau / t_step).astype(np.int)

        for i, shift in enumerate(shifts):
            diffs = df1[coords] - df1[coords].shift(-shift)
            sqdist = np.square(diffs).sum(axis=1)
            r = np.sqrt(sqdist)
            print(r)

        radial_disp = pd.DataFrame(data=r)

        return radial_disp

radial_d = radial (df1, frames, coords=['POSITION_X', 'POSITION_Y'])
print(radial_d)

As expected, the result is a huge number of sums in many columns, the problem is that I can see the results when I print r but the dataFrame that it generates only shows the last sum, which in fact is zero . How can I do to host all my r results in a data frame?

The example of what I want is the following:

for a df1

df1=
  X 
 10
 15
 25
 30'

the result would be:

'N1   N2
 5    15
 10   15
 5    NaN
    
asked by Jonathan Pacheco 11.05.2017 в 21:31
source

1 answer

3

The problem is when doing this:

for i, shift in enumerate(shifts):
    diffs = df1[coords] - df1[coords].shift(-shift)
    sqdist = np.square(diffs).sum(axis=1)
    r = np.sqrt(sqdist)
    print(r)

radial_disp = pd.DataFrame(data=r)

r is initialized with each cycle of for consequently when leaving the loop what you are going to get the last of the calculated values. You should go "accumulating" the values of r for example in a list

r = []
for i, shift in enumerate(shifts):
    diffs = df1[coords] - df1[coords].shift(-shift)
    sqdist = np.square(diffs).sum(axis=1)
    r.append(np.sqrt(sqdist))
    
answered by 12.05.2017 / 00:15
source