当我把一个不需要的列写到excel时,table()会把它放到我的数据框中为什么?

2024-04-26 01:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个有几十列的excel表中创建一个透视表。我从excel表中得到第三列,尽管它不在我的代码中。你知道吗

数据是这样的

源IP、目标IP、区域、连接、p/D、注释、位置、时间、备份、数据源 1.1.1.1,2.2.2.2,数据中心,3,P,装饰,FL,5X5,镜像,云 3.3.3.3,2.2.2.2,办公室,45,D,活动,ME,24X7,RAID,本地 1.1.1.1,4.4.4.4,办公,33,P,活动,CA,1X3,RAID,云

在Excel中手动创建透视表。试图用各种各样的理由来摆脱它。你知道吗

    fw_files = filedialog.askopenfilename()  #here we grab a filename to parse
    df = pd.read_excel(fw_files)
    df2 = df.drop_duplicates(['Source IP', 'Destination IP'])# lose the duplicates
    df3 = df2[df2['''P/D'''].str.contains('P', na=False)] #only flagged P and don't puke on NAN
    df4 = pd.pivot_table(df3, index=['Source IP', 'Destination IP'])# pivot on my two values
    writer = pd.ExcelWriter(fw_files + '-PIVOT.xlsx', engine='openpyxl')
    df3.to_excel(writer, sheet_name = 'RAW_DATA')
    df4.to_excel(writer, sheet_name = 'SOURCE_TO_DESTINATION')
    writer.save()

预期结果 源IP目标IP 10.120.160.71 172.1.12.5

172.1.1.5段

实际结果。我不知道为什么会出现连接列,但从excel表中看是正确的

源IP目标IP连接 10.120.160.71 172.1.12.8 3

172.34.4.5 45


Tags: toipsource目标dffilesexceldestination
2条回答

如果你能添加更多的源数据,让我们得到预期的结果,可能会有所帮助。我猜你得到的是因为你没有把“连接”列排除在外。默认情况下,Read Excel会拉取所有列,如果该列在数据框中,pivot\u表很可能会默认为为您聚合它,因为它是数字。你知道吗

您可以尝试仅将数据帧定义为所需的列。这至少应该为你指明正确的方向。你知道吗

df3 = df2.loc[df2['''P/D'''].str.contains('P', na=False), df2.columns.intersection(['Source IP', 'Destination IP'])]

编辑其他输出想法

我真的不知道为什么你只使用一个索引作为数据透视,因为一般情况下,数据透视将用于聚合。我认为你应该能够分组,因为你似乎不想要一个聚合。如果你想让输出看起来像那样,你可以设置索引和导出。输出看起来有点愚蠢,但它会以上面指定的格式在源值之间留下间隙。你知道吗

df:
          Source Destination
0  10.120.160.71  172.1.12.5
1  10.120.160.71   172.1.1.5
2  10.120.160.72  172.1.12.6
3  10.120.160.72   172.1.1.6

df = df.set_index(['Source','Destination'])

df.to_excel('df.xlsx')

          Source Destination
0  10.120.160.71  172.1.12.5
1                 172.1.1.5
2  10.120.160.72  172.1.12.6
3                 172.1.1.6

很难看,但我这样做就解决了

df4=df4.drop([“Connections”],轴=1)

然后写就可以了(从第2行开始)

相关问题 更多 >

    热门问题