Python 熊猫是修剪数据的更好方法
我目前有一个数据帧,看起来像这样:Python 熊猫是修剪数据的更好方法,python,database,pandas,Python,Database,Pandas,我目前有一个数据帧,看起来像这样: df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [100,100,30,40],'CCC' : [100,100,30,-50]}) 我还有数据框: df1 = pd.DataFrame({'AAA' : [4], 'BBB' : [100]}) 我定义的地方 relevantColumns=['AAA','BBB'] 这只是df1中包含的列的列表 我想找到df1出现在df中的索引。我现在有这样的东西 true
df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [100,100,30,40],'CCC' : [100,100,30,-50]})
我还有数据框:
df1 = pd.DataFrame({'AAA' : [4], 'BBB' : [100]})
我定义的地方
relevantColumns=['AAA','BBB']
这只是df1中包含的列的列表
我想找到df1出现在df中的索引。我现在有这样的东西
trueNFalses=(df==df1)[columnsToSort] #This generates a boolean dataframe
#Now I want to find the row with two trues in it, this is the row where df1 appears.
numTrues=trueNFalses.sum(axis=1)
#Now I look through numTrues and find the index of every values of 2,
#because that is where there were two trues.
indices=numTrues[numTrues==len(columnsToSort)].axes
所以我做了一个非常全面的计算,只是为了得到df有df1的列的索引。我觉得做所有这些都很愚蠢,因为我几乎可以肯定,在熊猫身上一定有更好的方法来做到这一点。我的技术也有一些缺点,我很想解决,但不知道如何解决。例如,我确实需要索引作为数据帧,但在我的代码中,它是一个数据类型对象的列表,这对于将来的处理来说是很麻烦的 我认为您可以尝试使用,然后索引值位于列index
:
df = pd.DataFrame({'AAA' : [4,5,6,7],
'BBB' : [100,100,30,40],
'CCC' : [100,100,30,-50]}, index=[2,3,4,5])
df1 = pd.DataFrame({'AAA' : [4], 'BBB' : [100]}, index=[8])
relevantColumns=['AAA','BBB']
print df
AAA BBB CCC
2 4 100 100
3 5 100 100
4 6 30 30
5 7 40 -50
print df1
AAA BBB
8 4 100
print pd.merge(df.reset_index(), df1, on=relevantColumns, how='right')
index AAA BBB CCC
0 2 4 100 100
print pd.merge(df.reset_index(), df1, on=relevantColumns, how='right')['index']
0 2
Name: index, dtype: int64
谢谢,这正是我要找的!!