首页 > 解决方案 > 循环根据名称与行内容相同的条件创建具有特定文件名和内容的输出文件

问题描述

我有一个包含 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

我该怎么做呢?

标签: pythonpandascsvdataframe

解决方案


不推荐使用动态命名的变量。它们难以跟踪,使命名空间混乱,导致错误。相反,您可以将字典理解与GroupBy.

例如,利用 f-strings (Python 3.6+),并假设您指定了stringsClient和:Channelfiledate

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)

推荐阅读