Change of sign of values in Pandas DataFrame

2

Hello, good evening.

I have a set of vectors whose components (px, py, and pz) are stored in a Pandas DataFrame. I have written a function whose purpose is to change the signal of the vector components if the following condition is observed:

If the value of pz is negative, then all components (including pz) of the vector must be multiplied by -1.

Below is the code I've tried so far:

Test DataFrame:

df = pd.DataFrame(np.random.randn(5, 3),
              index=['vec1', 'vec2', 'vec3', 'vec4', 'vec5'],
              columns=['px', 'py', 'pz'])

The function:

def change_sign(df):
    for value in df['pz'].values:
        if value >= 0:
            df['px_1'] = df['px']
            df['py_1'] = df['py']
            df['pz_1'] = df['pz']
        else:
            df['px_1'] = -df['px']
            df['py_1'] = -df['py']
            df['pz_1'] = -df['pz']

    return df

Role application:

change_sign(df)

The problem is that when I apply the function, the components of all vectors, even when pz is positive, are multiplied by -1. This should only happen when pz is less than 0.

I'm stuck because I'm not sure what I'm forgetting to do or what I'm doing wrong.

I'm running a virtual environment on Python 3.7.1 macros (Mini-deck 4.5.11), with pandas 0.23.4 and numpy 0.15.4.

Any help will be greatly appreciated.

Thank you.

    
asked by anonymous 03.12.2018 / 23:39

1 answer

0

[TL; DR]

I created a function that receives a dataframe, does not change it, and returns a modified one according to what you specify.

import pandas as pd
import numpy as np

def ch_sign(df):
    df2 = df.copy()
    for index, row in df2.iterrows():
        if row['pz'] < 0:
            row['px'] *= -1
            row['py'] *= -1
            row['pz'] *= -1
    return df2

a = np.array([[1, 2, -3], [4, 5, 6], [11, 22, -23], [-33, 44, 55], [77, 88,- 1]])
df = pd.DataFrame(a,index = ['vec1', 'vec2', 'vec3', 'vec4', 'vec5'], 
                    columns = ['px', 'py', 'pz'])

print("Vetor Original:", df, sep='\n')
Vetor Original:
      px  py  pz
vec1   1   2  -3
vec2   4   5   6
vec3  11  22 -23
vec4 -33  44  55
vec5  77  88  -1

print("Vetor Modificado:", ch_sign(df), sep='\n')
Vetor Modificado:
      px  py  pz
vec1  -1  -2   3
vec2   4   5   6
vec3 -11 -22  23
vec4 -33  44  55
vec5 -77 -88   1

See working at repl.it

    
04.12.2018 / 01:10