【问题标题】:Pandas Better Way To Trim DataPandas 修剪数据的更好方法
【发布时间】:2016-04-20 20:23:53
【问题描述】:

我目前有一个看起来像这样的数据框:

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 具有的列的索引。我觉得做这一切很傻,因为我几乎可以肯定在 pandas 中一定有更好的方法来做到这一点。我的技术也有一些我很想解决但不知道如何解决的缺点。例如,我确实需要将索引作为数据框,但在我的代码中,它是一个 dtype 对象列表,这对于未来的处理来说很尴尬。

【问题讨论】:

    标签: python database pandas


    【解决方案1】:

    我认为您可以尝试使用mergereset_index,然后索引值在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
    

    【讨论】:

    • 谢谢,这正是我要找的!
    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多