[SOLVED] python function iterates through list of sensor names and return result in dataframe


I have 2 sets of json files, one for co2 and one for temp each stored in co2_results and temp_results. I want to convert them into a pandas dataframe. So far I am using the below method which is not very efficient especially when I have a lot of json files.

co2_sensor1 = pd.DataFrame(co2_results[0])
co2_sensor2 = pd.DataFrame(co2_results[1])
co2_sensor3 = pd.DataFrame(co2_results[2])
temp_sensor1 = pd.DataFrame(temp_results[0])
temp_sensor2 = pd.DataFrame(temp_results[1])
temp_sensor3 = pd.DataFrame(temp_results[2])

Is there a way I can make the above code more efficient? Like using functions or for loops?

If I store them in a list:

my_list = ['co2_sensor1', 'co2_sensor2', 'co2_sensor3', 'temp_sensor1', 'temp_sensor2', 'temp_sensor3']

can i then iterate through this list based on indeces? (e.g. from index 0 to 2 take data from co2_results and then afterwards take results from temp_results and after return all the strings from my_list as df.


Try this:

my_list = [pd.DataFrame(i) for i in co2_results + temp_results]

This will iterate "pd.DataFrame()" for each item in a list combined from the two results list.

Answered By – ytung-dev

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *