【问题标题】:R parameter DROP equivalent in PandasPandas 中的 R 参数 DROP 等效项
【发布时间】:2014-02-20 12:51:49
【问题描述】:

我想知道以下 R 代码的 Python (Pandas) 等价物是什么:

outDataFrame <- myDataFrame[, rownames(inputDataFrame), drop=FALSE]
  • inputDataFrame 的行名与 myDataFrame 的列名相同。
  • myDataframe 的每一行只包含一个 TRUE 值(所有其他值都是 FALSE)

结果 outDataFrame 应该有:

  • 与 myDataFrame 行名称相同的行名称
  • 只有一列
  • 该列中包含的值应对应于值为 TRUE 的 myDataFrame 的列名

我希望它是可以理解的......

亲切的问候

R.

【问题讨论】:

    标签: python r select pandas


    【解决方案1】:

    一种方法是使用numpy.dot:

    >>> import numpy as np
    >>> import pandas as pd
    >>> df = pd.DataFrame ( { 'A':[False, True], 'B':[True, False] }, index=['row1', 'row2'] )
    >>> df
              A      B
    row1  False   True
    row2   True  False
    
    [2 rows x 2 columns]
    
    >>> pd.DataFrame( np.dot( df, df.columns ), index=df.index )
          0
    row1  B
    row2  A
    
    [2 rows x 1 columns]
    

    或者:

    >>> df.apply( lambda row: df.columns[row][0], axis=1 )
    

    输出pd.Series

    【讨论】:

    • 带布尔值和字符串的点??这到底是怎么回事?
    【解决方案2】:

    这是另一种方式,使用np.argmax

    In [55]: myDataFrame = pd.DataFrame([(True,False,False), (False,False,True), (False,False,True)], index=list('ABC'), columns=list('XYZ'))
    
    In [56]: myDataFrame
    Out[56]: 
           X      Y      Z
    A   True  False  False
    B  False  False   True
    C  False  False   True
    
    [3 rows x 3 columns]
    
    In [58]: pd.Series(myDataFrame.columns[np.argmax(myDataFrame.values, axis=1)], index=myDataFrame.index)
    Out[58]: 
    A    X
    B    Z
    C    Z
    dtype: object
    

    它很长,但可能更快,尤其是对于大型数据帧:

    In [76]: myDataFrame2 = pd.concat([myDataFrame]*10000)
    
    In [77]: %timeit pd.Series(myDataFrame2.columns[np.argmax(myDataFrame2.values, axis=1)], index=myDataFrame2.index)
    1000 loops, best of 3: 1.19 ms per loop
    
    In [78]: %timeit pd.Series( np.dot( myDataFrame2, myDataFrame2.columns ), index=myDataFrame2.index )
    100 loops, best of 3: 5.72 ms per loop
    
    In [79]: %timeit myDataFrame2.apply(lambda row: myDataFrame2.columns[row][0], axis=1)
    1 loops, best of 3: 1.15 s per loop
    

    【讨论】:

      【解决方案3】:

      对不起,我想我并不清楚实际上涉及两个数据框:

      我的输入是 df1 和 df2:

      df1 = pd.DataFrame([(True,False,False), (False,False,True), (False,False,True)],    index=list('XYZ'), columns=list('ABC'))
      df2 = pd.DataFrame([(1,2,1), (1,0,0), (1,1,1)], index=list('ABC'), columns=list('IJK'))
      

      结果应该是一样的:

         0
      X  A
      Y  C
      Z  C 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多