【问题标题】:How to return an empty value or None on pandas dataframe?如何在熊猫数据框上返回空值或无?
【发布时间】:2021-08-03 10:19:13
【问题描述】:

样本数据:https://docs.google.com/spreadsheets/d/1s6MzBu5lFcc-uUZ9B6CI1YR7P1fDSm4cByFwKt3ckgc/edit?usp=sharing

我有这个函数,它使用 textacy 来提取源属性。这会自动返回引用的说话者、提示和内容。在我的数据集中,有些段落有几个引号,但我只需要第一个,这就是我将 BREAK 放在 for 循环中的原因。

我现在的问题是一些原始数据没有引号,所以我希望函数不仅会跳过它,它还会返回一些东西。我相信问题出在EXCEPT之后:

它返回如下内容:

但它应该跳过第一行,因为第一行返回一个错误,所以我希望它看起来像这样:

import textacy 
from textacy import extract
import spacy

def extract_direct(text):
    extracted = pd.DataFrame()
    for i in text:
        try:
            doc = nlp(i)
            a = ex.direct_quotations(doc)
            for item in a:
                mined = {'speaker': item.speaker, 'cue': item.cue, 'content': item.content}
                extracted = extracted.append(mined, ignore_index = True)
                break
        except ValueError:
            continue
    contents = news_only['index']
    extracted = pd.concat([extracted, contents], ignore_index=True)
    return(extracted)

extract_direct(dataframe['Body'])

【问题讨论】:

  • 如果你试试这个df['content'].str.replace('(', '').str.replace(')', '').str.replace('",', '"').str.replace(',', ' ')
  • 我不明白替换如何解决这个问题
  • 你的帖子说,你想要什么,所以,当我看到你的原始 DF 并需要一个时,我感觉到 content 列中的差异,你有类似元组的值,但你正在剥离它们想要的结果,不是吗?

标签: python pandas dataframe textacy


【解决方案1】:

我这样做是为了解决问题。必须在 Try 和 except 处附加两个实例。

def extract_direct(text):
extracted = pd.DataFrame()
for i in text:
    try:
        doc = nlp(i)
        a = ex.direct_quotations(doc)
        for item in a:
            mined = {'speaker': item.speaker, 'cue': item.cue, 'content': item.content}
            extracted = extracted.append(mined, ignore_index = True)
            break
    except ValueError:
        mined = {'speaker': 'None', 'cue': 'None', 'content': 'None'}
        extracted = extracted.append(mined, ignore_index = True)
return(extracted)

【讨论】:

  • 很高兴你解决了这个问题。下次,您能否提供一个实际运行的代码示例,而不遗漏导入和变量定义?当您的问题发布后,人们很难为您提供帮助...请记住,您的问题越好,答案就越好
猜你喜欢
  • 2022-07-22
  • 2021-06-27
  • 2018-10-11
  • 2017-10-14
  • 1970-01-01
  • 2018-10-24
  • 2022-01-21
  • 2018-05-13
  • 2018-07-02
相关资源
最近更新 更多