Reputation: 177
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?
Upvotes: 0
Views: 488
Reputation: 33
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)
Upvotes: 1
Reputation: 4827
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
Upvotes: 1