使用其他数据帧中未包含的行创建一个新的数据帧



我需要在不创建新过滤器的情况下,用数据帧"结果"中未包含但在数据帧"df"上的行创建一个新的数据帧。

我不知道怎么做。你能帮我吗?(如果没有问题,抱歉(

import pandas as pd
#Creating dataframe
d = {'col1': [1, 2,3,4,5,6,7,8,9,10], 'col2': ['a','b','b','b','c','d','c','a','z','c']}
df = pd.DataFrame(data=d)
#Finding the lines that contain a certain letter
a = df[df['col2'].str.contains("a")]
b = df[df['col2'].str.contains("b")]
c = df[df['col2'].str.contains("c")]
#Merge the 3 data frames
frames = [a, b, c]
results = pd.concat(frames)
print(results)

更好的解决方案应该是通过所有3个掩码创建掩码,其中|用于OR,然后对于不匹配的行,通过~:反转掩码

m = df['col2'].str.contains("a|b|c")
results = df[m]
print(results)
col1 col2
0     1    a
1     2    b
2     3    b
3     4    b
4     5    c
6     7    c
7     8    a
9    10    c
df1 = df[~m]
print (df1)
col1 col2
5     6    d
8     9    z

您的解决方案应该通过过滤不匹配的索引值来更改:

df1 = df[~df.index.isin(results.index)]
print (df1)
col1 col2
5     6    d
8     9    z

首先连接df结果

new_df = pd.concat([df, results])

然后用keep=False参数删除所有重复项,从两个数据帧中删除所有公共条目,您将获得所需的数据帧

new_df = new_df.drop_duplicates(keep=False)

使用df.index.difference-将返回不在其他数据帧中的索引。

>>> df.iloc[df.index.difference(results.index)]
col1 col2
5     6    d
8     9    z

>>> df[~df.isin(results).all(1)]
col1 col2
5     6    d
8     9    z

最新更新