Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Python Pandas for loop/while loop question
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]

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]
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?

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.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Best Accuracy From Loop. AhmadMWaddah 4 206 Mar-17-2020, 10:25 PM
Last Post: stullis
  Interate for loop over certain columns in dataframe Finpyth 2 147 Mar-06-2020, 08:34 AM
Last Post: Finpyth
  newbie: loop, modify dataframe cells expat_th 5 220 Mar-03-2020, 09:05 PM
Last Post: jefsummers
  append dataframes in loop ghena 1 183 Feb-17-2020, 08:43 PM
Last Post: jefsummers
  prediction using linear regression (extrapolation?) in a loop karlito 0 291 Feb-05-2020, 10:56 AM
Last Post: karlito
  How do you put quotations around a result from a for loop? coder1384 14 296 Jan-18-2020, 02:46 PM
Last Post: coder1384
  please help making a loop faster carla_highlander 10 1,140 Nov-12-2019, 10:55 PM
Last Post: carla_highlander
  Counting Criteria in Pandas Question Koenig 1 285 Sep-30-2019, 05:16 AM
Last Post: perfringo
  Double 'for' loop and writing in a new columns dataframe marco_ita 0 325 Sep-07-2019, 12:44 PM
Last Post: marco_ita
  FOR loop not working properly marco_ita 0 249 Sep-07-2019, 08:40 AM
Last Post: marco_ita

Forum Jump:

Users browsing this thread: 1 Guest(s)