【发布时间】:2015-01-12 22:32:06
【问题描述】:
我想根据另一个数据帧中的数据从一个数据帧中删除数据。 我找到了一种方法来做到这一点(见下文),但我想知道是否有更有效的方法来做到这一点。 这是我要改进的代码:
# -*- coding: utf-8 -*-
import pandas as pd
#df1 is the dataframe where I want to remove data from
d1 = {'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.], 'three' : [5.,6.,7.,8.] }
df1 = pd.DataFrame(d1)
df1.columns = ['one', 'two', 'three'] #Keeping the order of the columns as defined
print 'df1\n', df1
#print df1
#I want to remove all the rows from df1 that are also in df2
d2 = {'one' : [2., 4.], 'two' : [3., 1], 'three' : [6.,8.] }
df2 = pd.DataFrame(d2)
df2.columns = ['one', 'two', 'three'] #Keeping the order of the columns as defined
print 'df2\n', df2
#df3 is the output I want to get: it should have the same data as df1, but without the data that is in df2
df3 = df1
#Create some keys to help identify rows to be dropped from df1
df1['key'] = df1['one'].astype(str)+'-'+df1['two'].astype(str)+'-'+df1['three'].astype(str)
print 'df1 with key\n', df1
df2['key'] = df2['one'].astype(str)+'-'+df2['two'].astype(str)+'-'+df2['three'].astype(str)
print 'df2 with key\n', df2
#List of rows to remove from df1
rowsToDrop = []
#Building the list of rows to drop
for i in df1.index:
if df1['key'].irow(i) in df2.ix[:,'key'].values:
rowsToDrop.append(i)
#Dropping rows from df1 that are also in df2
for j in reversed(rowsToDrop):
df3 = df3.drop(df3.index[j])
df3.drop(['key'], axis=1, inplace=True)
#Voilà!
print 'df3\n', df3
感谢您的帮助。
【问题讨论】:
-
当您说
df3 = df1时,df3将反映您对df1所做的任何更改,反之亦然。你应该说df3 = df1.copy()。 -
另外,这不是真正的连接操作;这是一个选择。我认为您应该编辑标题以反映这一点。
-
我正在尝试做的是这个网站codeproject.com/Articles/33052/… 所称的“不包括加入”。
-
但是您只想要其中一个数据框的列,对吧?连接用于对齐来自不同表的行和列。您所做的只是根据偶然存储在不同数据框中的元素来选择数据。有细微的差别。
标签: python pandas left-join inner-join dataframe