首页 > 解决方案 > 如何合并 2 个变量以便在使用 Pandas 时呈现标题

问题描述

几天前我开始使用 Python 时,请耐心等待,我正在尝试正确格式化波纹管,但无法弄清楚如何做到这一点,

我正在尝试从我的网络设备中格式化一些信息,使用 TextFSM 我设法提取我需要的信息,我想使用 Pandas 创建一个 Excel 表,以便正确格式化

输出图片下方

在此处输入图像描述

正如我所说我使用 TextFSM,所以变量 re_table 包含我的每一列的标题( re_table.header )这里是输出:

['port', 'Address', 'Ipaddress', 'Plateform']

我的 Pandas 数据框包含正确的信息,如下所示,但是显示时没有标题

    0                  1               2          3
0  46  98 f2 b3 4e 7c b0  172.27.254.212  HP J9774A
1  48                     172.27.254.210  Cisco IOS
2  48  24 e9 b3 a0 c8 80  172.27.254.210  Cisco IOS

我想合并 2 以便为我的列生成带有标题的 Excel 工作表,到目前为止我无法解决这个问题

我相信这只是连接代码的问题,但我无法弄清楚

def cdp():
    out = conn.send_command("show cdp neighbors detail")
    print(out)
    raw_text_data = out
    template = open("/root/ntc-templates/templates/hp_procurve_show_cdp_multiple.template")
    re_table = textfsm.TextFSM(template)
    fsm_results = re_table.ParseText(raw_text_data)
    cdp_result = re_table.header + fsm_results
    outfile_name = open("outfile.csv", "w+")
    outfile = outfile_name
    print(re_table.header)
    for s in re_table.header:
        outfile.write("%s," % s)
    outfile.write("\n")
    counter = 0
    for row in fsm_results:
        print(row)
        for s in row:
            outfile.write("%s," % s)
        outfile.write("\n")
        counter += 1
    print("Write %d records" % counter)
    print('Importing CDP info to a more structured way')
    dataframe = pd.DataFrame(fsm_results) # transpose the tables so interfaces are in a column
    #dataframe.sort_values(by=['port'], inplace=True) # sort the values by the "port" column we made
    #dataframe = dataframe.reset_index(drop=True) # reset the index to match this
    #dfColumns = dataframe.columns.tolist()
    #dataframe = dataframe[dfColumns]
    dataframe.to_excel('/root/'+ 'test.xls',index=False)
    print(re_table.header)
    print(dataframe)

我现在需要在最终脚本上合并2个Dataframe,这里是当前主脚本的df结构

    dataframe = pd.DataFrame(interfaceDict).T # transpose the tables so interfaces are in a column
    dataframe.sort_values(by=['port'], inplace=True) # sort the values by the "port" column we made
    dataframe = dataframe.reset_index(drop=True) # reset the index to match this


    # we want to re-order the columns, so we pull the names into a list
    dfColumns = dataframe.columns.tolist()

    # we change the order so that the "port" column header is first
    dfColumns.insert(0, dfColumns.pop(2))
    # then we re-insert that topology into the dataframe
    dataframe = dataframe[dfColumns]


    # finally we can export as an excel document
    dataframe.to_excel('/root/' + hostname + '.xls',index=False)

我需要合并数据框“fsm_results”,如果这有助于列标题端口与主数据框相同

这是主要数据框的结构:

port    mode    onlineCount status  vlan100 vlan101 vlan111 vlan118 vlan3000    vlan69  vlan805 vlan806 vlan851 vlan906

vlan 将始终根据交换机而有所不同,因此为什么端口是合并数据的最佳方式,如果有帮助,请在此处查看完整代码:https ://pastebin.com/42uH55pL

最好的方法是在之后插入第二个具有相同“端口”列的 DF,然后使用 mode/onlineCounter/Status 和 vlan

标签: pythonpandasdictionary

解决方案


您可以在之后设置列

dataframe.columns = re_table.header

或在声明中

dataframe = pd.DataFrame(fsm_results, columns=re_table.header)

文档

:索引或类似数组

用于生成的框架的列标签。如果没有提供列标签,将默认为 RangeIndex (0, 1, 2, ..., n)

要基于port列将两个表合并在一起,您可以使用pd.merge(). 检查以确保port列是相同的数据类型。您可以pd.to_numeric()如下所示使用我port在第一个数据框中设置为字符串的位置。

df1 = pd.DataFrame([
    ['46', '98 f2 b3 4e 7c b0',  '172.27.254.212',  'HP J9774A'],
    ['48', '',  '172.27.254.210',  'Cisco IOS'],
    ['48', '24 e9 b3 a0 c8 80',  '172.27.254.210',  'Cisco IOS'],
], columns=['port', 'Address', 'Ipaddress', 'Plateform'])
df1['port'] = pd.to_numeric(df1['port'])
print(df1)
#    port            Address       Ipaddress  Plateform
# 0    46  98 f2 b3 4e 7c b0  172.27.254.212  HP J9774A
# 1    48                     172.27.254.210  Cisco IOS
# 2    48  24 e9 b3 a0 c8 80  172.27.254.210  Cisco IOS

df2 = pd.DataFrame([
    [46, 100, 'Active'],
    [48, 42, 'Inactive']
], columns=['port', 'onlineCount', 'status'])
print(df2)
#    port  onlineCount    status
# 0    46          100    Active
# 1    48           42  Inactive

print(pd.merge(df1, df2, on='port'))
#    port            Address    ...    onlineCount    status
# 0    46  98 f2 b3 4e 7c b0    ...            100    Active
# 1    48                       ...             42  Inactive
# 2    48  24 e9 b3 a0 c8 80    ...             42  Inactive

可以在此处找到有关组合数据框的方法的更多信息。


推荐阅读