Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Try this:

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading