0

Pretty new to python so any help is appreciated. I am trying to generate multiple pandas dataframes from separate excel spreadsheets. However when I try to reference the dataframe later it returns as a list:

what I am trying is this

ref_dict = {}

... code to get the files open etc ...
        
        foo = []
        bar = []
        goo = []
        tar = []
        
        for z in range(40,c):
            foo_v = wb[n].cell(row=z, column=2).value
            bar_v = wb[n].cell(row=z, column=3).value
            goo_v = wb[n].cell(row=z, column=4).value
            tar_v = wb[n].cell(row=z, column=5).value
            foo.append(foo_v)
            bar.append(bar_v)
            goo.append(goo_v)
            tar.append(tar_v)
            d = {'Foo': foo, 'Bar': bar, 'Goo': goo, 'Tar': tar}
            df = pd.DataFrame(d)
            ref_dict[unique_ID] = []
            ref_dict[unique_ID] = [df]

.... later on ...

for i in ref_dict:
    print(type(ref_dict[i]))

The print type returns as a list and not a data frame - thus I cannot call columns etc. I could store multiple keys in a dict and assemble the dataframes later but it seems hacky and there should be a better way to do this?

2
  • 1
    [df] creates a list with one item (the dataframe). Commented Apr 25, 2021 at 20:52
  • Edit: Problems loop explanation helped me understand this further - thanks for the help! Thanks for the help but I dont think I understand what you are suggesting. When I do a print(type(df) after df.= pd.DataFrame(d) I get <class 'pandas.core.frame.DataFrame'>. Also when I try ref_dict[unique_ID] = [pd.DataFrame(d)] my for loop checking the value type still kicks back a list <class 'list'> Commented Apr 25, 2021 at 21:09

1 Answer 1

1

As mentioned in Michael's comment above, you assigned [df] as a value in your dictionary. If you want dataframes to be stored, then store them directly.

ref_dict[unique_ID] = df

If you really want them to be lists, then just access them like a list in a dictionary.

print(type(ref_dict[i][0]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This helped me understand Michaels comment further!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.