Python Forum

Full Version: proper syntax for itertuples?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have this code the keeps giving me errors. i cant seem to get the correct syntax, can anyone assist? below is the dataframe and error is: TypeError: tuple indices must be integers or slices, not str

for i in df.itertuples():
  if i['Close'] > i['prev']:
    i['trade2'] = '+'
    x = '+'
    continue
  elif i['Close'] < i['prev']:
    i['trade2'] = '-'
    x = '-'
    continue
  elif i['Close'] == i['prev']:
    i['trade2'] = x
[Image: uc?id=1tPZp-XC6NcJomwzbvx2UC4jDO5hDhz87]
You don't need to use loops for this task at all.

Something like this:

df.loc[df.loc[:, 'Close'] > df.loc[:, 'prev'], 'trade2'] = '+'
df.loc[df.loc[:, 'Close'] < df.loc[:, 'prev'], 'trade2'] = '-'
df.loc[df.loc[:, 'Close'] == df.loc[:, 'prev'], 'trade2'] = df.loc[((df.loc[:, 'trade2'] =='+')|df.loc[:, 'trade2'] == '-').last_valid_index()]['trade2']
should work.