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

标签 python string pandas

我有一个这样的数据框:

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'

最佳答案

您将需要应用一个函数来将元组连接到一个字符串。

df['all_words'] = df.words.apply(lambda x: ', '.join(', '.join([y[0]] * y[1]) for y in x))

关于python - 如何在 DataFrame 中将单词与数字相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216460/

相关文章:

python - pandas.read_excel 在 excel 中具有相同的列名

python - 根据 pandas 数据框中的特定列以及其他列在单独的列中按计数和总和进行分组

python - 在Pycharm中使用 'Execute Line in Console'时无法使用相对路径

python - 如何使用python识别中文或英文名字

Java System.getProperty ("line.separator") 在 apache 服务器中不工作

java - 在 ARM v6 上使用 java 将数字转换为字符串的性能

Python:我如何使用 itertools?

python - 什么是实现 __hash__() 的正确和好方法?

c# - ADO 命令文本语法

python - 将多列列表分解为行