Pandas合并会创建不需要的重复条目

时间:2017-02-24 16:50:46

标签: python pandas merge

我是Pandas的新手,我想合并两个具有相似列的数据集。除了许多相同的值之外,每个列都会与其他列相比具有一些唯一值。我希望保留每一栏中的一些重复内容。我想要的输出如下所示。添加how'= inner'或'outer'不会产生所需的结果。

import pandas as pd

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

print(pd.merge(df1,df2))

output:
   A
0  2
1  2
2  2
3  2
4  3
5  4
6  5

desired/expected output:
   A
0  2
1  2
2  3
3  4
4  5

请让我知道如何使用merge实现所需的输出,谢谢!

修改 哇这里有很多评论。为了澄清为什么我对这种行为感到困惑,如果我只是添加另一列,它不会产生四个2,而是只有两个2,所以我希望在我的第一个例子中它也会有两个2。为什么这种行为似乎会改变,熊猫在做什么?

import pandas as pd
dict1 = {'A':[2,2,3,4,5],
         'B':['red','orange','yellow','green','blue'],
        }
dict2 = {'A':[2,2,3,4,5],
         'B':['red','orange','yellow','green','blue'],
        }

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

print(pd.merge(df1,df2))

output:
   A       B
0  2     red
1  2  orange
2  3  yellow
3  4   green
4  5    blue

However, based on the first example I would expect:
   A       B
0  2     red
1  2  orange
2  2     red
3  2  orange
4  3  yellow
5  4   green
6  5    blue

4 个答案:

答案 0 :(得分:1)

import pandas as pd

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1).reset_index()
df2 = pd.DataFrame(dict2).reset_index()

df = df1.merge(df2, on = 'A')
df = pd.DataFrame(df[df.index_x==df.index_y]['A'], columns=['A']).reset_index(drop=True)

print(df)

输出:

   A
0  2
1  2
2  3
3  4
4  5

答案 1 :(得分:0)

你尝试过df.drop_duplicates()吗?

import pandas as pd

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

df=pd.merge(df1,df2)
df_new=df.drop_duplicates() 
print df
print df_new

似乎它提供了你想要的结果

答案 2 :(得分:0)

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1)
df1['index'] = [i for i in range(len(df1))]
df2 = pd.DataFrame(dict2)
df2['index'] = [i for i in range(len(df2))]

df1.merge(df2).drop('index', 1, inplace = True)

我们的想法是根据匹配指数进行合并以及匹配' A'列值。
以前,由于合并工作的方式取决于匹配,所发生的是df1中的前2个与df2中的第一个和第二个匹配,而df1中的第二个2与df2中的第一个和第二个匹配为好。

如果你试试这个,你会看到我在说什么。

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1)
df1['index'] = [i for i in range(len(df1))]
df2 = pd.DataFrame(dict2)
df2['index'] = [i for i in range(len(df2))]

df1.merge(df2, on = 'A')

答案 3 :(得分:-1)

很不幸,我偶然发现了一个类似的问题,我发现它已经很老了。 我通过以不同的方式使用此函数来解决此问题,将其应用于两个原始表,即使这些表中没有重复项也是如此。这是一个例子(对不起,我不是专业程序员):

import pandas as pd

dict1 = {'A':[2,2,3,4,5]}
dict2 = {'A':[2,2,3,4,5]}

df1 = pd.DataFrame(dict1)
df1=df1.drop_duplicates()

df2 = pd.DataFrame(dict2)
df2=df2.drop_duplicates()

df=pd.merge(df1,df2)
print('df1:')
print( df1 )

print('df2:')
print( df2 )

print('df:')
print( df )
相关问题