簡體   English   中英

如何在pandas中使用用戶自定義的function根據列值和Timestamp返回一個值

[英]How to return a value based on column value and Timestamp using user-defined function in pandas

我有兩個dataframe,我已經加入了。 在加入的 Dataframe 上,我正在編寫一個用戶定義的 function,其中基於時間戳和列的值計數,我需要根據下面提到的條件返回值,創建一個名為“Day_Sentiment”的新列。 但是我遇到了以下錯誤。 請讓我知道如何 go 關於它

輸入:

                  Date          Content    Cleaned-content   Sentiment   
                  11/12/2020    abb        bbc abb           Bad         
                  12/10/2020    xyz        xxy               Good        
                  11/24/2020    tyu        yuu               Neutral     
                  12/16/2020    iop        yui               Bad         

Output:

               Date          Content    Cleaned-content   Sentiment   Day_Sentiment
               11/12/2020    abb        bbc abb           Bad         Bad
               12/10/2020    xyz        xxy               Good        Bad
               11/24/2020    tyu        yuu               Neutral     Bad
               12/16/2020    iop        yui               Bad         Bad

到目前為止,我在下面嘗試過:

df = input_data.join(results)

def compare_def(df):

    no.bad_senti= df.loc[df['Sentiment'] == 'Bad']
    no.neut_senti = df.loc[df['Sentiment'] == 'Neutral']
    no.good_senti= df.loc[df['Sentiment'] == 'Good']

    if ((no.bad_senti> no.good_senti) & (no.bad_senti> no.neut_senti)):
       output = 'Bad'
    elif ((no.good_senti> no.bad_senti) & (no.good_senti> no.neut_senti)):
       output= 'Good'
    elif ((no.neut_senti> no.bad_senti) & (no.neut_senti> no.good_senti)):
       output= 'Neutral'
    elif no.good_senti== no.bad_senti:
       output= 'Neutral'
    elif no.bad_senti== no.neut_senti:
       output= 'bad'
    elif no.good_senti== no.neut_senti:
       output= 'good'
    else:
       output= 'Neutral'

    return output

df['Day_Sentiment'] = output

備用:

 output = compare_def(df)
 df['Day_Sentiment'] = output

錯誤:

     ValueError: Can only compare identically-labeled DataFrame objects

示例 1:預測情緒 情緒 2 壞 1 好 1 中性

然后在 function 2 > 1 和 2 > 1 返回 Bad

示例 2:情緒:2 壞 5 好 5 中性

Function:

2 > 5 false 5 > 2 and 5 > 5 false 5 > 2 and 5 > 5 false 5==2 false 2==5 false 5==5 True 返回 good

您的代碼有幾個問題。 首先,變量 bad、good 和 neut 是包含字符串變量的不同長度的熊貓系列。 然后您嘗試評估執行幾個條件測試,例如if ((bad> good) & (bad> neut)會生成您的 ValueError。我不太確定您嘗試實現的邏輯是什么,但以下模板可能會有所幫助:

def compare_data(row):
    value = 'Good'
    # The logic here escapes me
    # Evaluate the row contents of row[Sentiment] and modify value
    return value  

df["Day Sentiment"]= df.apply(lambda row: compare_data(row), axis= 1)

產量:

    Date    Content Cleaned-content Sentiment   Day Sentiment
0   11/12/2020  abb bbc abb Bad Good
1   12/10/2020  xyz xxy Good    Good
2   11/24/2020  tyu yuu Neutral Good
3   12/16/2020  iop yui Bad Good

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM