python - 如何使用列表作为变量输入在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文件。有什么想法吗?
解决方案
似乎您只需要一个简单的for
循环:
for amenity in amenity_options:
df[df['amenity'] == amenity].to_excel(f"{amenity}_amenity.xlsx")
推荐阅读
- parsing - 解析和词性标注有什么区别?
- angular - 单击相邻元素时,如何创建自定义角度指令以显示和隐藏子元素?
- r - 动画点直方图,通过观察构建观察(在 R 中使用 gganimate)
- asp.net - 生成一个类别的产品列表
- r - 为什么在绘图时排序的数据框会重新排列?
- php - PHP中的组合字符串和数字两个多维数组的总和
- flutter - 为什么我添加 TextToSpeech 会出错?
- ios - 仅在 iOS 中渲染本地静态图像(React Native)
- reactjs - 如何防止useLayoutEffect定义的按钮功能在渲染后自动执行
- wpf - WPF处理触摸板上的捏缩放