猿问

如何在 DataFrame 中将单词与数字相乘?

我有一个这样的数据框:


print(df.words[0])

[('replacement', 1), ('shaver', 2)]


print(df.words[1])

[('filter', 2), ('purifier', 1), ('please', 2)]

我想创建一个名为“all_words”的新列。该列应该代表真实的字符串,而不是数字。


('head', 3) should be: "head,head,head"

示例的所需输出:


print(df.all_words[0])

'replacement, shaver, shaver'



print(df.all_words[1])

'filter, filter, purifier, please, please'


qq_花开花谢_0
浏览 116回答 4
4回答

哆啦的时光机

您将需要apply一个函数来将元组连接到单个字符串。df['all_words'] = df.words.apply(lambda x: ', '.join(', '.join([y[0]] * y[1]) for y in x))

泛舟湖上清波郎朗

你可以这样做df.apply()将熊猫导入为 pddf = pd.DataFrame({'words' : [[('replacement', 1), ('shaver', 2)], [('filter', 2), ('purifier', 1), ('please', 2)]]})def word_to_words(row):    words_string = ''    for tuple_set in row['words']:        words_string += (tuple_set[0] + ', ') * tuple_set[1]    return(words_string)df['all_words'] = df.apply(word_to_words, axis=1)

慕姐8265434

您可以使用apply:df = pd.DataFrame(data=[[[('filter', 2), ('purifier', 1), ('please', 2)]]], columns=['words'])result = df.words.apply(lambda x: ', '.join(word for word, count in x for _ in range(count)))print(result)输出0    filter, filter, purifier, please, pleaseName: words, dtype: object

翻过高山走不出你

它只是解决 thorug 循环及其工作原理。如果单词是多个元组的列表words = [[('replacement', 2), ('shaver', 2) ], [('filters', 2), ('purifier',1), ('plears', 3) ]]Loop = words[0] #here you use indexing of words[0] or [1] bothResult = ()for val in Loop:    v = tuple([val[0] * 1 for _ in range(val[1])])    Result = Result + vPrint(Result) 
随时随地看视频慕课网APP

相关分类

Python
我要回答