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

Time:07-31

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?

CodePudding user response:

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

CodePudding user response:

there may be more elegant solutions but as simplest one I would create two new columns and add the one based on np.where.

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

for i in range(len(li)):
  if int(i)%2!=0:
    new_column2.append('sell')
  else:
    new_column2.append('buy')

print(new_column1) # 
print(new_column2) #


new_column2
df['dir']=np.where(df['dir'].iloc[0]=="buy", new_column2, new_column1)

of course to create new columns list comprehantion could be used.

  • Related