【问题标题】:Dataframe does not accept results from lambda functionDataframe 不接受 lambda 函数的结果
【发布时间】:2021-11-21 14:50:23
【问题描述】:

我正在编写一个带有分类器的情感分析器,其中模型、情感函数调用和分类器函数调用都适用于单独的文本行。现在我正在尝试将它们应用于实时数据,不知何故 lambda 函数的结果不会在数据框中编码。

如果您知道任何解决方法,请告诉我。

谢谢!

下面是实时数据测试的代码:

#File to open
live_file  = r'C:\Users\jan.von.v.n.alcoba\Desktop\FY21 Consolidated EOC\Test_Dataset.xlsx'

#Load Spreadsheet
xl = pd.ExcelFile(live_file)

#print sheet names
print(xl.sheet_names)

#load excel file and store in dataframe
live_df = pd.read_excel(xl,sheet_name='Sheet1')
live_df

live_df['Feedback'] = live_df['Feedback'].apply(lambda x: str(x))
live_df['Sentiment'] = live_df['Feedback'].apply(lambda x: predict_sentiment(x))
live_df['Classification'] = live_df['Feedback'].apply(lambda x: predict_classification(x))
live_df

结果如下所示:

Code Output:

这是之前的live_df.head():

enter image description here

这是 live_df.head() 之后: enter image description here

【问题讨论】:

  • 代码看起来不错...哪个应用程序不起作用?你可以在调用之前和之后发布live_df.head()吗?
  • 欢迎来到 SO。你的问题非常不清楚。期望的结果是什么,实际的结果是什么?您的大部分代码都引用了我们没有的数据。 stackoverflow.com/help/minimal-reproducible-example
  • @JuanR 我已经在前后发布了 live_df.head()。

标签: python-3.x pandas numpy-ndarray sentiment-analysis


【解决方案1】:

我已经解决了我的问题。答案在于只输出 None 类型的函数调用。需要使用 return 函数而不是 print 函数来返回函数的输出,以便数据框接受 lambda 的结果。

def predict_sentiment(text):
    twt = tokenizer.texts_to_sequences([text])
    twt = pad_sequences(twt, maxlen=40, dtype='int32', value=0)
    prediction = model.predict(twt, batch_size=1,verbose=2)[0]
    if(np.argmax(prediction) == 0):
        #print("AFI")
        return "AFI"
    elif (np.argmax(prediction) == 1):
        #print("Strength")
        return "Strength"

【讨论】:

  • 这就是我们要求最少可重复示例的原因。
猜你喜欢
  • 2020-04-27
  • 2022-01-09
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2021-12-23
  • 2019-02-13
相关资源
最近更新 更多