【问题标题】:Find the name of the column in a Pandas DF which contains the longest list在 Pandas DF 中查找包含最长列表的列的名称
【发布时间】:2017-08-22 21:24:17
【问题描述】:

给定一个 Pandas DataFrame,其中列表存储在几列中,有没有一种简单的方法可以找到包含每行最长列表的列名?

例如,使用以下数据:

                          positive                 negative          neutral
1   [marvel, moral, bold, destiny]                       []   [view, should]
2                      [beautiful]      [complicated, need]               []
3                      [celebrate]   [crippling, addiction]            [big]

我想将“肯定”标识为第 1 行列表最长的列,第 2 行和第 3 行标识为“否定”。

我想我可以使用str.len() 来计算列表长度和idmax() 来获取列名,但不知道如何组合它们。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    IIUC:

    In [227]: df.applymap(len).idxmax(axis=1)
    Out[227]:
    0    positive
    1    negative
    2    negative
    dtype: object
    

    【讨论】:

    • 非常感谢!快速跟进:idxmax() 在 'positive'、'negative' 和 'neutral' 都是空列表时返回第一个索引(即 'positive')。可以修改此解决方案以忽略此类行吗?我尝试用 NaN 替换空列表,但 len 然后抱怨:"object of type 'float' has no len()"
    • @user2950747,你能提供一个可重现的数据集吗?
    • this sample data 在倒数第三行有空列表,idxmax() 将标记为“肯定”。
    • @user2950747,你只是想删除这些行吗?
    • 啊...是的!我没有那样想,但这将是最简单的方法。谢谢!
    【解决方案2】:
    >>> df.apply(lambda row: row.apply(len).argmax(), axis=1)
    0    positive
    1    negative
    2    negative
    dtype: object
    

    【讨论】:

      【解决方案3】:

      或者你可以试试这个...

      df=df.reset_index()
      DF=pd.melt(df,id_vars=['index'])
      DF['Length']=DF['value'].apply(lambda x : len(x))
      DF.sort_values(['index','Length']).drop_duplicates(subset=['index'],keep='last')
      

      【讨论】:

        猜你喜欢
        • 2018-05-31
        • 2020-12-13
        • 1970-01-01
        • 2013-12-20
        • 2020-08-30
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多