首页 > 解决方案 > 如何使用列表作为变量输入在python中循环命令?

问题描述

这是我在编码社区的第一篇文章,所以我希望在我的帮助请求中得到正确的详细信息!

背景信息:
我想使用包含选项列表的变量在 df 中重复(循环)命令。虽然系列 ' amenity_options ' 包含一个简单的特定项目列表(假设只有四个便利设施,如下例所示),但 df 是一个包含许多其他项目的大型数据框。我的目标是为“ amenity_option ”中的每个项目运行以下操作,直到列表末尾。

amenity_options = ['cafe','bar','cinema','casino'] # this is a series type with multiple options

df = df[df['amenity'] == amenity_options] # this is my attempt to select the the first value in the series (e.g. cafe) out of dataframe that contains such a column name.

df.to_excel('{}_amenity.xlsx, format('amenity') # wish to save the result (e.g. cafe_amenity) as a separate file.

期望的结果:
我希望为列表中的每个可用项目(例如咖啡馆、酒吧、电影院......)循环第一步和第二步。这样我最后会有单独的excel文件。有什么想法吗?

标签: pythonpandasfor-loop

解决方案


似乎您只需要一个简单的for循环:

for amenity in amenity_options:
    df[df['amenity'] == amenity].to_excel(f"{amenity}_amenity.xlsx")

推荐阅读