【问题标题】:Python - Pandas replacing dataframe column values - column data stored as list (i.e., '[this, that,'])Python - Pandas 替换数据框列值 - 列数据存储为列表(即,'[this,that'])
【发布时间】:2020-01-12 11:37:55
【问题描述】:

我已经尝试了很多不同的东西,我假设我在这里很近。我有一个由 Gensim 关键字摘要器提供的研究摘要生成的单词列表。数据是准确的,但是它存储为每行的列表,我想摆脱每行的 [' 和 '] 。我尝试了下面的代码和不同的变体,但要么我收到错误,要么代码处理但没有替换。我试过了:

 #scenario 1
 keywords = ['screened', 'model', 'health',  'volume']
 df['newnlpkeywords'] = keywords
 df['newnlpkeywords'].replace("']", "", inplace=True)

 #scenario 2

 keywords = ['screened', 'model', 'health',  'volume']
 df['newnlpkeywords'] = keywords.replace(replace("']", "")

我知道这是一个菜鸟问题,但我正在努力学习!我想在尝试 30 分钟后,我应该寻求帮助。谢谢!

【问题讨论】:

  • 你得到了什么输出,你想得到什么输出?
  • 假设 newnlpkeywordslist 而不是 str 类型,其中包含括号,您可以使用 df["newnlpkeywords"] = df["newnlpkeywords"].apply(lambda x: ", ".join(x))。如果变量是str 类型,那么你应该可以做到df["newnlpkeywords"].str.replace(r"\[|\]", "")
  • 我的输出实际上是列表,如 ['screened', 'model', 'health', 'volume']
  • @brittenb - 成功了,谢谢!

标签: python pandas list text replace


【解决方案1】:

这就是你要找的东西

import numpy as np
import re

rgx = lambda x: re.sub("']","",x)

rgx = np.vectorize(rgx)

df['newnlpkeywords'].values = rgx(df['newnlpkeywords'].values)

以下代码将 rgx 函数应用于 df['newnlpkeywords'] 中的每一行

(我知道可能有更多的 Pythonic 方法可以做到这一点,但这是一个快速修复,我相信有一个更简洁的答案)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2018-02-11
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多