DSantos
DSantos

Reputation: 19

How can I apply a If-function to a Dataframe

I'm very new to Pandas and I've been trying to build an if-stetament function to apply in a dataframe column.

I need a function to look for each row in the column 'type of inflow' and then depend on the kind of the letter assign a positive or negative number on a new column called 'cash flow'.

df = {'type of inflow':['I', 'D', 'I', 'D', 'R', 'D'], 'historic value':[100, 300, 200, 700, 400, 600]}

 def cash_flow(row):

     if row['type of inflow'] == "I" or row['type of inflow'] == "D":

        row['type of inflow'] = row['historic value'] * -1

     elif row['type of inflow'] == "R":

        row['cash flow'] = row['historic value'] * 1

Thanks in advance

Upvotes: 0

Views: 106

Answers (1)

DarrylG
DarrylG

Reputation: 17156

The Pandas Apply Function can be used.

import pandas as pd

# Define dataframe
df = pd.DataFrame({'type of inflow':['I', 'D', 'I', 'D', 'R', 'D'], 'historic value':[100, 300, 200, 700, 400, 600]})

def cash_flow(row):
  " Change function to return desired value based upon columns "
  if row['type of inflow'] == "I" or row['type of inflow'] == "D":
    return row['historic value'] * -1

  elif row['type of inflow'] == "R":
    return row['historic value'] * 1

# use Appy to generate cash flow colum using the cash_flow function
df['cash flow'] = df.apply(lambda row: cash_flow(row), axis = 1)
print(df)

Output

 type of inflow  historic value  cash flow
0              I             100       -100
1              D             300       -300
2              I             200       -200
3              D             700       -700
4              R             400        400
5              D             600       -600

Upvotes: 1

Related Questions