0

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

DSantos
  • 19
  • 4
  • 1
    have a look at this link : https://stackoverflow.com/questions/43391591/if-else-function-in-pandas-dataframe. Depending on your case, you could use numpy.where or numpy.select. As much as possible, try and avoid looping through each row and use a vectorized method. – sammywemmy Jan 25 '20 at 00:37
  • For first if condition, should `row['type of inflow'] = row['historic value'] * -1` be `row['cash flow'] = row['historic value'] * -1`? – DarrylG Jan 25 '20 at 00:50
  • Stack Overflow is not a substitute for guides, tutorials, or documentation. If you're learning to use a new library, your first reflex should always be to read the documentation. https://pandas.pydata.org/pandas-docs/stable/ – AMC Jan 25 '20 at 03:53
  • 1
    Does this answer your question? [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column) – AMC Jan 25 '20 at 03:53

1 Answers1

1

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
DarrylG
  • 16,732
  • 2
  • 17
  • 23