Python Forum
proper syntax for itertuples?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
proper syntax for itertuples?
#1
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]
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyserial issues with proper loops and binary jttolleson 16 2,621 Nov-02-2023, 08:39 PM
Last Post: deanhystad
  [split] How to access previous row using itertuples newoptionz 1 660 Feb-28-2023, 04:43 PM
Last Post: deanhystad
  Getting proper x,y axis values pyhill00 8 1,669 Jul-29-2022, 06:48 PM
Last Post: pyhill00
  Proper way to do the OR statement? Mark17 5 1,774 Mar-01-2022, 01:54 PM
Last Post: Mark17
  How to access previous row using itertuples SriRajesh 7 7,649 Feb-07-2022, 09:24 AM
Last Post: perfringo
  proper use of 'end' in a 'with' statement ccrider27 1 2,065 Mar-18-2020, 10:33 PM
Last Post: buran
  Proper use of if..elif..else statement nick1941 2 2,420 Mar-06-2020, 11:22 PM
Last Post: nick1941
  Proper Layout of Code Question TheJax 2 2,206 Feb-08-2020, 06:14 PM
Last Post: TheJax
  Unable to do the proper split using re.sub incase of missing data. Karz 1 1,868 Nov-17-2019, 05:58 PM
Last Post: buran
  getopt with tuple not working proper Frank123456 0 1,881 Aug-21-2019, 12:46 PM
Last Post: Frank123456

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020