簡體   English   中英

如何根據 dataframe 列的唯一值創建文本文件?

[英]How to create a text file based on the unique values of a dataframe column?

我有一個 excel 表,其中有 2 列稱為('NE' 和 'Interface'),我想要做的是:使用每個接口值編輯 a.txt 文件模板(我已經有了,我在下面顯示) . 然后連接屬於同一組'NE'的txt文件。

這是我的 excel:

擅長

這是我的 txt 文件模板,我想用 excel 的接口值更改“接口”:

conf t
**$interface**   
no service-policy input QOS-IN_ACCESS
end
conf t
no policy-map QOS-IN_ACCESS 
policy-map QOS-IN_ACCESS 
class DSCP_VOIX_SIG 
set mpls experimental imposition 5 
set qos-group 5 
end
conf t
**$interface**   
service-policy input QOS-IN_ACCESS
end

這是我的代碼:(我已經連接了文件,我需要做的是把它們放在一組 NE 中)

from string import Template
import pandas as pd

df3 = pd.read_excel(r"C:\Users\audit_policymap.xlsx")
with open(r"C:\Users\audit_policymap.txt") as fp:
    template = Template(fp.read())

content2 = ''
content3 = ''
for i in range(len(df3)):
    file_name = df.loc[i, "NE"] + '_output.txt'
    with open(file_name, 'w') as fp:
        content = template.substitute(interface=df.loc[i, "Interface"]) 
        if  df.loc[i, "NE"] == df.loc[i+1, "NE"]:
            content2 = str(content2)+'\n'+str(content)+'\n'
            content3 = str(content2)+'\n'
            fp.write(content2)
        else:  
            content2 = ''
            content3 = str(content3)+'\n'+str(content)+'\n'
            fp.write(content3)

總結:我希望每個 'NE' 有一個 txt 文件,並根據它們對應的 'NE' 編輯所有接口

  • NE列上使用pandas.DataFrame.groupby
    • 這將返回一個DataFrameGroupBy object,其中i是來自NE的唯一 groupby 值, g是關聯組。
    • for 循環將遍歷NE中的每個唯一值
  • 使用 f 字符串指定唯一的文件名(例如f'{i}_output.txt'
    • '250002-PEFTTS-2_output.txt'
  • 由於g中的所有值僅屬於NE中的唯一值之一,因此無需檢查NE是否與每一行匹配,就像您在問題中所做的那樣。
  • [str(template.substitute(interface=row)) for row in g.Interface]是一個列表理解,對於g.Interface中的每一行,將str(template.substitute(interface=row))添加到列表中。
    • '\n'.join()將列表中的每個項目連接為由換行符分隔的字符串。
for i, g in df.groupby('NE'):  # iterate through unique values in NE
    file_name = f'{i}_output.txt'  # create the empty content string
    with open(file_name, 'w') as fp:  # open the file
        content = '\n'.join([str(template.substitute(interface=row)) for row in g.Interface])
        fp.write(content)  # write content to file

暫無
暫無

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

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