python - 循环根据名称与行内容相同的条件创建具有特定文件名和内容的输出文件
问题描述
我有一个包含 n # 行的文件。我正在阅读文件并将其分配给数据框df
。列名称之一是curr_state
. 基于curr_state
,我想为每个特定的curr_state
. 输出文件必须遵循特定的名称约定。我已经使用以下代码单独完成了此操作:
#curr_state: curr.state
#to extract rows that contain current state "curr.state"
CurrStateName= (df.loc[df['curr_state'] == 'curr.state'])
#naming convention
OutputCurrStateName = "abc_" +str(Client) + "_" + str(Channel) + "_" + "CurrStateName" + "_" + str(filedate) + ".csv"
#output file to a csv file
CurrStateName.to_csv(OutputCurrStateName, sep=',', encoding='utf-8', index=False)
但是,我希望读取另一个包含curr_state
列表及其CurrStateName
对应文件的 csv 文件,curr_state
并在循环中使用命名约定创建输出文件。
包含 curr_state 的文件
curr_state. CurrStateName
hello.attempt HelloAttempt
Goodbye.attempt GoodbyeAttempt
我该怎么做呢?
解决方案
不推荐使用动态命名的变量。它们难以跟踪,使命名空间混乱,导致错误。相反,您可以将字典理解与GroupBy
.
例如,利用 f-strings (Python 3.6+),并假设您指定了stringsClient
和:Channel
filedate
d = {f'abc_{Client}_{Channel}_{state}_{filedate}': df_state \
for state, df_state in df.groupby('curr_state')}
然后,您可以通过迭代数据框字典来输出 CSV 文件:
for k, v in d.items():
v.to_csv(f'{k}.csv', sep=',', encoding='utf-8', index=False)
推荐阅读
- scala - In Scala is it possible to create class object of class which takes generic
- python-3.x - Optimize the time it take to read txt file
- ruby-on-rails - 如何在 rails4-autocomplete gem 上添加条件,例如(其中 user_id 是 user.id)
- include - 如何在 sequelizejs 中使用 orderBy 和 include
- scrapy - Scrapy Splash 返回空列表
- c++ - 使用 libcurl 多接口连续请求相同的“简单”句柄
- winapi - 'Avl' 后缀与 Win32 API 中的原始函数有什么区别?
- c# - LINQ - 带有布尔方法的 Where 子句
- javascript - Javascript show/hide on dropdown onchange 函数,表单提交后需要记住值
- python - Python,每行中的项目到一个变量