两个Dataframe,其中一个列的列数多于另一个 - >减去并合并

时间:2016-11-14 10:30:05

标签: python csv pandas python-3.5

好的,我知道标题可能有点混乱,但我会尝试详细解释这个:

我使用Python 3.5.2:

我有两个.csv文件,我通过pandas读取并转换为两个独立的数据帧。第一个数据帧(来自XYZ.csv)如下所示:

ip              community
10.0.0.1        OL123
.
.
.
123.12.5.31    IK753

第二个(export.csv)只有" ip"列。

现在我想做什么:

我想比较两个数据帧,结果获得第三个数据帧(或列表),其中包含第一个数据帧中的所有IP地址,但不包含其相关社区中的所有IP地址。到目前为止,只要第二个数据帧也包含社区,我设法比较两者并获得正确的结果。我手动将这些社区插入到第二个export.csv中,遗憾的是我不能自动执行此操作,这就是为什么我需要在没有包含社区的第二个数据帧的情况下工作。

这是我的代码:

def compare_csvs():
         timestamp = time.strftime("%Y-%m-%d")

    # Reads XYZ.csv and creates list that contains all ip addresses in integer format.
         A = pd.read_csv("XYZ.csv", index_col=False, header=0)
         ips1 = A.ip.tolist()
         comu1 = A.ro_community.tolist()
         AIP = []
         for element1 in ips1:
                  AIP.append(int(ipaddress.IPv4Address(element1)))
         IPACOM1 = zip(AIP,comu1)              

    # Reads export.csv and creates list that contains all ip addresses in integer format.
         B = pd.read_csv("export" + timestamp + ".csv", index_col=False, header=0)
         ips2 = B.ip.tolist()
         comu2 = B.ro_community.tolist()
         BIP = []
         for element2 in ips2:
                  BIP.append(int(ipaddress.IPv4Address(element2)))
         IPACOM2 = zip(BIP,comu2)

    # Creates a set that contains all ip addresses (in integer format) that exist inside the XYZ.csv but not the export.csv.
         DeltaInt = OrderedSet(IPACOM1)-OrderedSet(IPACOM2)
         List = list(DeltaInt)
         UnzippedIP = []
         UnzippedCommunity = []
         UnzippedIP, UnzippedCommunity = zip(*List)

    # Puts all the elements of the DeltaInt set inside a list and also changes the integers back to readable IPv4-addresses.
         DeltaIP = []
         for element3 in UnzippedIP:
              DeltaIP.append(str(ipaddress.IPv4Address(element3)))

         IPandCommunity = zip(DeltaIP,UnzippedCommunity)

现在我需要的是可以比较我创建的两个列表并保持"社区"用" ip"它被分配给。我尝试了很多,但我似乎无法得到任何工作。也许我只是在这里遇到逻辑问题,所有的帮助都表示赞赏!

此外,请原谅代码混乱,我只是把所有这些放在一起,并在代码实际工作后清理它。

1 个答案:

答案 0 :(得分:1)

以下是一些虚拟数据:

这是df:

ip              community
10.0.0.1        OL123
10.1.1.1        ACLSH
10.9.8.7        OKUAJ1
123.12.5.31     IK753

df = pd.read_clipboard()

这是export.csv:

s_export = pd.Series(s_export = pd.Series(name='ip', data=['10.1.1.1','123.12.5.31', '0.0.0.0'])

s_export

0       10.1.1.1
1    123.12.5.31
2        0.0.0.0
Name: ip, dtype: object

要选择那些不在导出中的,我们可以使用isin()简单地使用布尔索引:

# ~ means 'not', so here that's "find df.ip that is NOT in s_export"
# Store result in a dataframe
df_exclude = df[~df.ip.isin(s_export)]


df_exclude
         ip community
0  10.0.0.1     OL123
2  10.9.8.7    OKUAJ1