neanderslob
neanderslob

Reputation: 2693

How can I use a variable value to call a dataframe?

Say that I'm given a dataframe that summarizes different companies:

summary=pandas.DataFrame(columns=['Company Name', 'Formation Date', 'Revenue', 'Profit', 'Loss'])

And then say each company in that dataframe has its own corresponding dataframe, named after the company, giving a more in-depth picture of the company's history and stats. Something like:

exampleco=pandas.Dataframe(columns=['Date', 'Daily Profit', 'Daily Loss', 'Daily Revenue'])

I have a script that processes each row of the summary dataframe, but I would like to grab the name from row['Company Name'] and use it to access the company's own dataframe.

In other words I'd love it if there was something that worked like this:

.
.
>>> company=row['Company Name']
>>> pandas.get_dataframe_from_variable(company)

Empty DataFrame
Columns: ['Date', 'Daily Profit', 'Daily Loss', 'Daily Revenue']
Index: []

[0 rows x 2 columns]
.
.

Any ideas of how I might get this to work would be much appreciated.

Thanks in advance!

Upvotes: 3

Views: 5803

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53688

You can use a dictionary to contain your DataFrames and use strings as the keys.

companies = {'company1':pandas.DataFrame(columns=['Date', 'Daily Profit', 
                                                 'Daily Loss', 'Daily Revenue']), 
             'company2':pandas.DataFrame(columns=['Date', 'Daily Profit',
                                                 'Daily Loss', 'Daily Revenue'])}

company=row['Company Name'] # Get your company name as a string from your summary.
company_details = companies[company] # Returns a DataFrame.

Upvotes: 1

Related Questions