簡體   English   中英

循環以根據名稱與行內容相同的條件創建具有特定文件名和內容的輸出文件

[英]loop to create output files with specific file names and content based on condition where name will be same as row content

我有一個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)

不過,我期待閱讀包含另一個csv文件curr_state列表和CurrStateName對應於curr_state ,並在一個循環的命名慣例創建輸出文件。

包含curr_state的文件

curr_state.                 CurrStateName
hello.attempt             HelloAttempt
Goodbye.attempt      GoodbyeAttempt

我該怎么做呢?

不建議使用動態命名的變量。 它們難以跟蹤,名稱空間混亂,導致錯誤。 相反,您可以對GroupBy使用字典理解。

例如,利用f字符串(Python 3.6+),並假設您指定了字符串ClientChannelfiledate

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM