4 回答
TA贡献1779条经验 获得超6个赞
您将需要apply
一个函数来将元组连接到单个字符串。
df['all_words'] = df.words.apply(lambda x: ', '.join(', '.join([y[0]] * y[1]) for y in x))
TA贡献1818条经验 获得超3个赞
你可以这样做df.apply()
将熊猫导入为 pd
df = 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)
TA贡献1813条经验 获得超2个赞
您可以使用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, please
Name: words, dtype: object
TA贡献1875条经验 获得超3个赞
它只是解决 thorug 循环及其工作原理。如果单词是多个元组的列表
words = [[('replacement', 2), ('shaver', 2) ], [('filters', 2), ('purifier',1), ('plears', 3) ]]
Loop = words[0] #here you use indexing of words[0] or [1] both
Result = ()
for val in Loop:
v = tuple([val[0] * 1 for _ in range(val[1])])
Result = Result + v
Print(Result)
添加回答
举报