How to change values of pandas dataframe based on the first row value

Question:

I have this dataframe:

dir

buy
buy
buy
buy

I want that if the value of the first row is "buy", so do this:

dir

buy
sell
buy
sell

If, instead, the value of the first row is "sell", do this:

dir

sell
buy 
sell
buy

any ideas?

Asked By: Pren Ven

||

Answers:

DataFrame 1:

df = pd.DataFrame({'dir': ['buy']*4})
if df.loc[0, 'dir'] == 'buy':
    df.loc[df.index % 2 != 0, 'dir'] = 'sell'
print(df)

Output:

    dir
0   buy
1  sell
2   buy
3  sell

DataFrame 2:

df = pd.DataFrame({'dir': ['sell']*4})    
if df.loc[0, 'dir'] == 'sell':
    df.loc[df.index % 2 != 0, 'dir'] = 'buy'
print(df)

Output:

    dir
0  sell
1   buy
2  sell
3   buy
Answered By: René

There might be more elegant solutions but as the simplest one I would create two new columns and add the one based on numpy.where().

li = ['sell','buy','buy','buy','buy']
df = pandas.DataFrame(li, columns=['dir'])
new_column1 = ['sell' if i % 2 == 0 else 'buy' for i in range(len(li))]
new_column2 = ['sell' if i % 2 != 0 else 'buy' for i in range(len(li))]


print(new_column1)
print(new_column2)


df['dir'] = np.where(df['dir'].iloc[0] == "buy", new_column2, new_column1)
Answered By: Zaur
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.