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

4
  • 1
    have a look at this link : stackoverflow.com/questions/43391591/…. 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. Commented Jan 25, 2020 at 0:37
  • For first if condition, should row['type of inflow'] = row['historic value'] * -1 be row['cash flow'] = row['historic value'] * -1? Commented Jan 25, 2020 at 0: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. pandas.pydata.org/pandas-docs/stable Commented Jan 25, 2020 at 3:53
  • 1
    Does this answer your question? Pandas conditional creation of a series/dataframe column Commented Jan 25, 2020 at 3:53

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.