Claire
Claire

Reputation: 3

Create a new column based on another column's content

I am trying to create a new column called returns_direction based on contents of returns column. if returns are positive, 1 for return_direction or 0 otherwise.

Here is my code:

for i in df['returns']:
    if df['returns'][i] > 0:
        df['returns_direction'][i] == 1
    else:
        df['returns_direction'][i] == 0
    
df.head()

But what I got is a KeyError: 0.0154199803149606, how can I fix this?

Upvotes: 0

Views: 80

Answers (1)

rustyhu
rustyhu

Reputation: 2157

You misuse i in for i in df['returns']: as an index, it is assigned as the element value, such as the 0.0154199803149606 in your data.

If you need to use the corresponding index for df['returns_direction']:

# Create new column first
df['returns_direction'] = 0

# Assign values
for i, v in enumerate(df['returns']):
    if v > 0:
        df['returns_direction'][i] = 1
    else:
        df['returns_direction'][i] = 0

# or concisely
for i, v in enumerate(df['returns']):
    df['returns_direction'][i] = (1 if v > 0 else 0)

Upvotes: 1

Related Questions