Pandas最好的修剪方法

2024-10-02 18:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个数据帧,看起来像这样:

df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [100,100,30,40],'CCC' : [100,100,30,-50]})

我还有一个数据框:

^{pr2}$

在我定义的地方

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拥有的索引,df拥有df1所拥有的列。我觉得这么做很愚蠢,因为我几乎可以肯定在熊猫身上肯定有更好的方法。我的技术也有一些缺点,我很想解决,但不知道如何解决。例如,我确实需要索引作为一个数据帧,但在我的代码中,它是一个dtype对象的列表,这对于以后的处理来说是很困难的。在


Tags: the数据df列表findnowrowdf1
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:12

我想您可以用^{}尝试^{},然后索引值在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

相关问题 更多 >