0

I'm capturing a value from a primary table to apply as a variable later, using this code:

#capturing value of the month
month = str(DF['COLUMN'].max())[6:7]

#reading the xlsx where I want to look for the number of the month 
file = pandas.read_excel('myfile.xlsx', sheet_name='sheet1',engine='openpyxl')
mycolumns= file.columns.values.tolist()

Then I made a loop to use this value as a variable.

for i in mycolumns:
    if i == month :
        this_month = i

but when I use this value as variable to try to get all the values in this single column, like this:

file.loc[:,f'{this_month}']

I get a key error :/

KeyError:'VariableName'

I tryed to execute as a list, as array and tryed to strip the empty spaces as a result from research, like thisbut nothing work for me. Also tryed to change the type of the month variable of str to int and vice versa. Do u guys have some suggestions?

here's a dump df that follows the same format that mine

data = {'1' : ['50000','70000','90000','872'],
    '2' : ['8394' , '83704','94809','02984'],
    '3' : ['3664' , '74637','39847','38984']
    }
df   = pd.DataFrame(data) 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
karolyna
  • 11
  • 2
  • I don't understand the `for` loop. Isn't it just the same as `this_month = month`? – Barmar Jun 30 '23 at 18:53
  • When you do `print(this_month)` is it what you expect? – Barmar Jun 30 '23 at 18:56
  • @Barmar I tryied this right now but the keyError continues. That says something? – karolyna Jun 30 '23 at 19:01
  • It doesn't fix the error, it's for debugging why it's failing. Does it print a column name from the dataframe? – Barmar Jun 30 '23 at 19:02
  • You're not looking for a value in a list. `file` is a dataframe. – Barmar Jun 30 '23 at 19:02
  • Yes! @Barmar I get an output of 6, the way I expected and match with the value that i capture – karolyna Jun 30 '23 at 19:03
  • And if you do `file.loc[:, '6']` it works? – Barmar Jun 30 '23 at 19:06
  • The same error, @Barmar. :/ just to respond your previous contribution, Im trying to use 6 as an identifier to capture the values of the column with same name in my df – karolyna Jun 30 '23 at 19:12
  • Please post a [mre] with a sample dataframe. – Barmar Jun 30 '23 at 19:13
  • @Barmar I just edit the publication with that dump df – karolyna Jun 30 '23 at 19:24
  • Can you also add `file.head` output? – Barmar Jun 30 '23 at 19:27
  • What is the column name you're using in `df['column'].max()`? – Barmar Jun 30 '23 at 19:28
  • Dear @Barmar Thank for helping, your contribution allow me to think about some possibilities that i didn't try by myself. Sometimes we just need to get out of our head. The problem was that i was giving file.loc[:,f'{this_month}'] with FORMAT and the code was looking for a string, but just found numbers. I tryed file.loc[:,this_month] and works fine for me. – karolyna Jun 30 '23 at 19:44

0 Answers0