简体   繁体   English

python function 遍历传感器名称列表并在 dataframe 中返回结果

[英]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.我有两套 json 文件,一套用于 co2,一套用于 temp,每个文件都存储在 co2_results 和 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.我想将它们转换成 pandas dataframe。到目前为止,我使用的是下面的方法,它不是很有效,尤其是当我有很多 json 文件时。

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?喜欢使用函数或 for 循环?

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?然后我可以根据索引遍历这个列表吗? (eg 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. (例如,从索引 0 到 2 从 co2_results 获取数据,然后从 temp_results 获取结果,然后将 my_list 中的所有字符串作为 df 返回。

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.这将为两个结果列表组合的列表中的每个项目迭代“pd.DataFrame()”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM