我有這樣的數據框(df1
):比較Python的熊貓DataFrames用於匹配行的熊貓
df1 = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'))
print df1
A B C D
0.860379 0.726956 0.394529 0.833217
0.014180 0.813828 0.559891 0.339647
0.782838 0.698993 0.551252 0.361034
0.833370 0.982056 0.741821 0.006864
0.855955 0.546562 0.270425 0.136006
0.491538 0.445024 0.971603 0.690001
0.911696 0.065338 0.796946 0.853456
0.744923 0.545661 0.492739 0.337628
0.576235 0.219831 0.946772 0.752403
0.164873 0.454862 0.745890 0.437729
我想檢查是否從另一個數據框(df2
)的任何行(所有列)存在於df1
。這是df2
:
df2 = df1.ix[4:8]
df2.reset_index(drop=True,inplace=True)
df2.loc[-1] = [2, 3, 4, 5]
df2.loc[-2] = [14, 15, 16, 17]
df2.reset_index(drop=True,inplace=True)
print df2
A B C D
0.855955 0.546562 0.270425 0.136006
0.491538 0.445024 0.971603 0.690001
0.911696 0.065338 0.796946 0.853456
0.744923 0.545661 0.492739 0.337628
0.576235 0.219831 0.946772 0.752403
2.000000 3.000000 4.000000 5.000000
14.000000 15.000000 16.000000 17.000000
我試圖用df.lookup
在一次搜索一行。我就是這麼做的:
list1 = df2.ix[0].tolist()
cols = df1.columns.tolist()
print df1.lookup(list1, cols)
,但我得到這個錯誤信息:
File "C:\Users\test.py", line 19, in <module>
print df1.lookup(list1, cols)
File "C:\python27\lib\site-packages\pandas\core\frame.py", line 2217, in lookup
raise KeyError('One or more row labels was not found')
KeyError: 'One or more row labels was not found'
我也嘗試使用.all()
:
print (df2 == df1).all(1).any()
,但我得到這個錯誤信息:
File "C:\Users\test.py", line 12, in <module>
print (df2 == df1).all(1).any()
File "C:\python27\lib\site-packages\pandas\core\ops.py", line 884, in f
return self._compare_frame(other, func, str_rep)
File "C:\python27\lib\site-packages\pandas\core\frame.py", line 3010, in _compare_frame
raise ValueError('Can only compare identically-labeled '
ValueError: Can only compare identically-labeled DataFrame objects
我也是trie d isin()
這樣的:
print df2.isin(df1)
,但我得到False
無處不在,這是不正確的:
A B C D
False False False False
False False False False
False False False False
False False False False
False False False False
False False False False
False False False False
False False False False
False False False False
False False False False
是否可以搜索在數據幀一組行,通過比較其他數據幀的行?
編輯: 如果這些行也存在於df1
中,是否可以刪除df2
行?
哦當然!一個SQL'INNER JOIN'。這逃脫了我。一個問題是,我從來沒有使用'JOIN'ing'ON'多列。如果要檢查所有數據框的列,可以用'on = df1.columns'來代替'on = ['A','B','C','D']'嗎? – 2015-04-06 02:37:01
您可以使用'on = list(df1.columns)'或等效的'on = list(df2.columns)'。如果要檢查行是否相同(所有列),則df1和df2中的列必須相同。 – Andrew 2015-04-06 02:55:19
安德魯,最後一個問題(我也將它添加到原始文章中) - 確定了來自'df2'的行也存在於第一個數據框('df1')中,是否有可能將「pd .merge()'然後從'df2'中刪除同樣出現在'df1'中的行? – 2015-04-06 20:40:51