Python Forum
Python Pandas for loop/while loop question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Pandas for loop/while loop question
#1
Hi I created the following dataframe:

df = pd.DataFrame([['a', 'car', 1], ['b', 'bus', 2], ['c', 'limo', 3]])
df.columns = ['letter', 'trans', 'num']

I am attempting to create a for or while loop to create a vector that returns the num column by recognizing the letter column (basically a vlookup) (also I know I can just do pd.num to get this vector but how I wrote this loop is kind of similar to something I'm doing at work and I am getting the same kind of errors but can't figure out why.)

The for loop is:

letter = ['a','b','c']
tr = []
for i in letter:
k = df[df.letter == str(i)]
k1 = k['num'][0]
tr.append(k1)

The while loop is:

letter = ['a', 'b', 'c']
tr = []
i = 0
while i <= len(df.num)-1:
k = df[df.letter == df.letter[i]]
k1 = k['num'][0]
tr.append(k1)
i = i + 1

In Juptyer notebook it is saying the error comes from k1 line and says a key error but I am confused when I repeat the code at put 'a' instead of df.letter[i] just to test one case, it works for each letter.

Can anyone explain why this isn't working or how to fix it?

Thanks
Reply
#2
I think you are expecting k['num'] to return a list or closure. but it returns a DataFrame. The first time through the for loop the dataframe is [0 1] (what symbol does one use to denote a dataframe instead of a list or closure?) When you ask for k['num'][0] this works because the dataframe contains a zero. The second time through the loop k['num'] returns the dataframe [1 2]. This does not contain zero, so k['num'][0] raises a key error.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pandas df inside a df question mbaker_wv 4 1,152 Dec-25-2022, 01:11 AM
Last Post: mbaker_wv
  Pandas usecols question rsearing 1 1,218 Aug-20-2022, 10:10 PM
Last Post: jefsummers
  Simple pandas question mcva 4 2,607 Dec-17-2021, 04:47 PM
Last Post: mcva
  Matplotlib scatter plot in loop with None values ivan_sc 1 2,236 Nov-04-2021, 11:25 PM
Last Post: jefsummers
  while loop mazeemagha 2 1,766 Aug-28-2021, 03:24 PM
Last Post: naughtyCat
Question I want to vectorize a really long for loop to improve performance Miregal1 1 1,891 Jul-18-2021, 11:13 AM
Last Post: jefsummers
  change for loop into numpy functions ToffiFaye 1 1,944 Feb-06-2021, 11:38 AM
Last Post: paul18fr
  Pandas question new2datasci 0 1,928 Jan-10-2021, 01:29 AM
Last Post: new2datasci
  Change classic loop to TensorFlow tf.while_loop vsl_neuro 0 1,749 Dec-15-2020, 07:57 AM
Last Post: vsl_neuro
  Python PDF merging from an excel pandas for loop siraero 0 2,165 Aug-16-2020, 09:34 AM
Last Post: siraero

Forum Jump:

User Panel Messages

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