嗨,毕多纳人和毕多尼斯人,
我有一个工作代码,它将三个过滤器应用于一个dataframe。该代码应用于194个实例,这会增加可承受级别上的总运行时间--所以现在我需要减少它。
我的代码:
1_all =df.loc[(df‘’Country‘== '1') &(df’‘Unit’== "Result") &(df‘’Structure‘==“总计”)]
2_all =df.loc[(df‘’Country‘== '2') &(df’‘Unit’== "Result") &(df‘’Structure‘==“总计”)]
3_all =df.loc[(df‘’Country‘== '3') &(df’‘Unit’== "Result") &(df‘’Structure‘==“总计”)]
4_all =df.loc[(df‘’Country‘== '4') &(df’‘Unit’== "Result") &(df‘’Structure‘==“总计”)]
是否有可能将这些代码转换为循环函数,这会减少整个运行时间吗?
提前谢谢你们-堆叠溢出救了我不止一次。
发布于 2022-05-10 11:51:45
您可以创建一个groupby对象并对其进行循环。
只在单元/结构上过滤一次:
dfs = {name: g for name,g in
(df.loc[(df['Unit'] == "Result") & (df['Structure'] == "Total")]
.groupby('Country'))
}然后,您可以使用
dfs['1'] # assuming '1' is a stringhttps://stackoverflow.com/questions/72185436
复制相似问题