Signal change of values in Pandas Dataframe

Asked

Viewed 338 times

2

Hello, good night.

I have a set of vectors whose components (px, py and Pz) are stored in a Dataframe Pandas. I wrote a function whose goal is to change the signal of the components of the vectors if the following condition is observed:

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

Below follows the code I have 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

Application of the function:

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 don’t know what I’m forgetting to do or what I’m doing wrong.

I’m running a virtual environment on macOS from Python 3.7.1 (Miniconda 4.5.11), with pandas 0.23.4 and numpy 0.15.4.

Any help would be most welcome.

Thank you.

1 answer

0


[TL;DR]

I designed a function that receives a dataframe, does not change it and returns another modified according to what Voce specifies.:

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 on repl it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.