[英]Get the largest element of a list from a DataFrame column
I have a DataFrame like this:我有一个这样的 DataFrame:
df = pd.DataFrame({
'Names':[['John','Stefan'], ['Stacy','Jennifer'], ['Paul','Sean', 'Alu']],
})
What I would like to do is to create a new column with the longest word present in a list from column "Names".我想做的是创建一个新列,其中包含“名称”列列表中最长的单词。 Also, in case there are 2 or more words with the same largest number of char in them, I would like to return both.
此外,如果有 2 个或更多单词的最大字符数相同,我想返回两个。
So the output should look like this:所以 output 应该是这样的:
| Names | Output |
| ----------------- | ------------|
| [John, Stefan] | Stefan |
| [Stacy, Jennifer] | Jennifer |
| [Paul, Sean, Alu] | Paul, Sean |
I know that for a single list one can do maybe something like this:我知道对于一个列表,一个人可以做这样的事情:
sorted = sorted(my_list, key=len)
largest_element = sorted[-1]
But how to iterate in case of a list in a DataFrame column and how to extract more than 1 largest element in case there is a tie in the number of max char?但是如何在 DataFrame 列中的列表的情况下进行迭代,以及如何提取超过 1 个最大元素以防最大字符数相等?
Does anybody know?有人知道吗?
Try:尝试:
def get_max(x):
m = len(max(x, key=len))
return ', '.join(w for w in x if len(w) == m)
df['Output'] = df['Names'].apply(get_max)
print(df)
Prints:印刷:
Names Output
0 [John, Stefan] Stefan
1 [Stacy, Jennifer] Jennifer
2 [Paul, Sean, Alu] Paul, Sean
You can write a function and apply it to every row.您可以编写一个 function 并将其应用于每一行。
def get_largest(names_list):
sorted_list = sorted(names_list, key=len)
largest_word = sorted_list[-1]
longest_length = len(largest_word)
largest_words = [word for word in names_list if len(word)==longest_length]
return largest_words
df = pd.DataFrame({'Names': [['John', 'Stefan'], ['Stacy', 'Jennifer'], ['Paul', 'Sean', 'Alu']]})
df['Output'] = df['Names'].apply(get_largest)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.