2

I am using Pandas to sort through an excel spreadsheet. I would like to execute an if/elif function to return a string in a new column within my dataframe. I am trying to return a new column named "action" that returns a string based off time values.

state     time      
 ca         1
 ca         5
 ca         7
 ca         10

for rows in df:

 if df[time]>=1:
    return "do nothing"

 elif df[time]<=5:
     return "add more"

 elif df[time]<=10:
      return "add less"

  else:
      return "error"
2
  • do you have a more specific question or error? Commented Sep 19, 2017 at 21:03
  • please accept answers that solved your questions Commented Oct 8, 2017 at 14:45

3 Answers 3

4

IIUC we can use pd.cut() method:

In [167]: df['new'] = pd.cut(df.time, 
                             bins=[-np.inf, 1, 5, 10, np.inf], 
                             labels=['do nothing','add more','add less','error'])

In [168]: df
Out[168]:
  state  time         new
0    ca     1  do nothing
1    ca     5    add more
2    ca     7    add less
3    ca    10    add less
Sign up to request clarification or add additional context in comments.

Comments

2

Using np.searchsorted

labels = np.array(['do nothing', 'add more', 'add less', 'error'])
df.assign(new=labels[np.searchsorted([1, 5, 10], df.time.values)])

  state  time         new
0    ca     1  do nothing
1    ca     5    add more
2    ca     7    add less
3    ca    10    add less

Comments

0

The following code is a simple way to add a column for each condition in pandas.

import pandas as pd
from io import StringIO

csv = StringIO("""state,time
ca,1
ca,5
ca,7
ca,10""")
df = pd.read_csv(csv)
# Out[1]:
#   state  time
# 0    ca           1
# 1    ca           5
# 2    ca           7
# 3    ca          10

def add_action(row):
    if row["time"] <= 1:
        return "do nothing"
    elif row["time"] <= 5:
        return "add more"
    elif row["time"] <= 10:
        return "add less"
    else:
        return "error"

df = df.assign(action=df.apply(add_action, axis=1))
# Out[2]: 
#   state  time      action
# 0    ca     1  do nothing
# 1    ca     5    add more
# 2    ca     7    add less
# 3    ca    10    add less

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.