【问题标题】:Rearrange row upon column value根据列值重新排列行
【发布时间】:2021-12-24 01:40:04
【问题描述】:

我有一个 DataFrame,我想在其中重新排列给定列的数据。

我有什么:

    text                                                KEYWORD
0   Fetch.ai will transform economies, healthcare,...   supplies chain issues
1                                                       self
2                                                       secured key partnership
3                                                       real world challenge
4                                                       autonomous economic agent
5                                                       learning traffic signal
6                                                       autonomous machine learning
7                                                       disruptive ai tech
8                                                       parking issues
9                                                       traffic reduction
10      
11      
12  The two most popular cryptocurrencies on the p...   bitcoin
13                                                      limited supplies
14                                                      ethereum
    

我想要什么:

    text                                                KEYWORD
0   Fetch.ai will transform economies, healthcare,...   supplies chain issues, self, secured key partnership,  real world challenge, autonomous economic agent, learning traffic signal, autonomous machine learning, disruptive ai tech, parking issues, traffic reduction
1   The two most popular cryptocurrencies on the p...   bitcoin, limited supplies, emphasized text, ethereum

包含文本的每一行都显示在“文本”列中。 “文本”列已被分析并从中提取关键字并显示在“关键字”列中。烦人的部分是,如果从“文本”列中提取 10 个关键词,它将创建 10 行,每行添加 1 个关键词。我想将所有这些关键字加入一行(对应于好文本)。

很遗憾,我无法访问由软件完成的关键字提取过程。

【问题讨论】:

  • 请不要将您的数据发布为屏幕截图。阅读它(使用pd.read_csv 或您喜欢的任何内容)并将输出作为代码发布。第 3 行、第 4 行等中的文本是否为空字符串,例如 "" 或 NaN
  • @not_speshal 对此感到抱歉。它们是空字符串“”

标签: python pandas dataframe keyword-extraction


【解决方案1】:

试试groupby:

#replace blank cells with NaN
df = df.replace(r"^\s*$",np.nan,regex=True)

#drop rows that are all NaN and forward fill
df = df.dropna(how="all").ffill()

#groupby and aggregate
output = df.groupby("text", as_index=False)["KEYWORD"].agg(", ".join)

>>> output
                                                text                                            KEYWORD
0  Fetch.ai will transform economies, healthcare,...  supplies chain issues, self, secured key partn...
1  The two most popular cryptocurrencies on the p...                bitcoin, limited supplies, ethereum

【讨论】:

  • 感谢您的帮助。不幸的是,它不起作用。使用真正的df,它会复制带有关键字数量的文本。我将在上面的问题中添加信息。
  • @Loremima - 是的,它复制了输入 DataFrame 中的文本。但我认为你只需要output。有什么关系?
  • 实际上它确实有效,我的错。非常感谢!!
  • 乐于助人!我正在编辑以匹配您的新示例。所以看看这是否更好。
猜你喜欢
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2017-12-27
相关资源
最近更新 更多