【问题标题】:How to create n copies of every row on dataframe based value in list Python如何在列表 Python 中基于数据框的值创建每一行的 n 个副本
【发布时间】:2021-07-15 19:18:20
【问题描述】:

我有以下数据框

| Domain   | Description 
| test.com | some string
.....

我有一个文本增强算法,它接受一个字符串作为输入并返回带有10 修改字符串的列表。我们称这个函数为def augmentation(text)

对于数据框中的每一行,我想对 Description 列进行扩充,并为每行创建 10 个副本,并将值从 augmentation 函数传递给 Description。 预期的结果应该类似于:

| Domain   | Description 
| test.com | some string
| test.com | smoe string
| test.com | moe sring
| test.com | some sring
..... and so on.

【问题讨论】:

  • 试试:df=df.reindex(df.index.repeat(10)).reset_index(drop=True)
  • 感谢您的回答,但在您的方法中,它会创建 10 个行副本,但在我的情况下,我想像 apply 一样传递函数扩充,并根据返回的列表中的每个值创建 n 行功能

标签: python pandas


【解决方案1】:

我想出了以下方法

df['Description'] = df['Description'].apply(augmentation)
result = df.assign(Description=df['Description']).explode('Description').reset_index(drop=True)

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2018-12-22
    • 2020-08-24
    • 2020-06-15
    • 1970-01-01
    • 2022-07-29
    • 2021-05-24
    • 2022-12-06
    • 2019-08-09
    相关资源
    最近更新 更多