Home > Software engineering >  Writing a Python script where a function code is ran on 3 variables on an imported panda csv file af
Writing a Python script where a function code is ran on 3 variables on an imported panda csv file af

Time:08-12

What can I do so the ss variable can read all x,y, and z variables? Currently, it just reads the x variable from the csv file (the file has three variables in it and I wish to create a 4th called w in which the function result is saved).

Screenshot of function and code

CodePudding user response:

# create dataframe with 3 columns' random values
import pandas as pd
import numpy as np
ss = pd.DataFrame({
    'A':[1,2,3,4,5,6],
    'B':[7,8,9,10,11,12],
    'C':[13,14,15,16,17,18]
})
ss
###
   A   B   C
0  1   7  13
1  2   8  14
2  3   9  15
3  4  10  16
4  5  11  17
5  6  12  18


Function

def compute(x):
    x = x.astype(float)
    return x['A']**3   2*x['B']**2   3*x['C']

ss['D'] = compute(ss)
print(ss)
###
   A   B   C      D
0  1   7  13  138.0
1  2   8  14  178.0
2  3   9  15  234.0
3  4  10  16  312.0
4  5  11  17  418.0
5  6  12  18  558.0


dataframe type

print(ss.dtypes)
###
A      int64
B      int64
C      int64
D    float64
dtype: object

CodePudding user response:

You can reference those columns from your csv by using the element index, like this:

  def compute(cols)
      x = float(cols[0])
      y = float(cols[1])
      z = float(cols[2])

You also need to pass the columns from your dataframe as a list by enclosing in [] and include axis=1 in your apply method so that the function is applied across the rows of your dataset.

ss["w"] = ss[["x","y","z"]].apply(compute, axis=1)
  • Related