在包含最长列表的Pandas DF中找到列的名称 [英] Find the name of the column in a Pandas DF which contains the longest list
本文介绍了在包含最长列表的Pandas DF中找到列的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个Pandas DataFrame,其中的列表存储在多个列中,是否有一种简单的方法来查找包含每行最长列表的列名?
Given a Pandas DataFrame with lists stored in several of the columns, is there a simple way to find the column name which contains the longest list for each row?
例如,使用以下数据:
positive negative neutral
1 [marvel, moral, bold, destiny] [] [view, should]
2 [beautiful] [complicated, need] []
3 [celebrate] [crippling, addiction] [big]
我想将正"标识为第1行的列表最长的列,将负"标识为第2行和第3行的列表.
I want to identify "positive" as the column with the longest list for row 1 and "negative" for rows 2 and 3.
我以为我可以用str.len()
计算列表长度,用idmax()
获取列名,但是不知道如何组合它们.
I thought I could use str.len()
to calculate the list lengths and idmax()
to get the column names, but can't figure out how to combine them.
推荐答案
IIUC:
In [227]: df.applymap(len).idxmax(axis=1)
Out[227]:
0 positive
1 negative
2 negative
dtype: object
这篇关于在包含最长列表的Pandas DF中找到列的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文