簡體   English   中英

將用戶定義的 function 應用於 python dataframe 中特定列的所有行

[英]Apply a user defined function to all rows of a specific column in python dataframe

我很難將用戶定義的 function 應用於 python dataframe 中的特定列。 dataframe 是同胞:

Year    state   Narrative
----------------------------------
2015      WV   a roof fall occurred at 10:05 am at 10+50 entry 6 in 8lms mmu 010, .. more text
2016      AL   a rib rolled out striking him on his left foot resulting ...... more text
2017      CO   a non-injury mountain bump occurred inby the 5n longwall. additional ... more text

我想根據“敘述”預測接地故障的類型,以便在 dataframe 中添加一個新列,如下所示。 我通過在“narrative”中查找一些關鍵字來預測地面塌陷,例如:如果“narrative”包含以下任何單詞['roof fall', 'roof broke', 'rock fell from the top'] ,地面墜落預測應該是“屋頂墜落”。

這是我生成的用戶定義的 function,但它不起作用。

def predict_groundFall(narrative):
    fall_dict = {'roof fall': ['Roof fall', 'roof broke', 'rock fell from the top'],
                 'rib fall': ['rib fall ', 'rib rolled', 'rib dislodged'],
                 'outburst': ['outburst', 'bounce', 'rockburst']}
    for key, values in fall_dict.iteritems():
        if values in narrative:
            return key
            break
df['predicted_failure'] = df.apply( lambda row:  predict_groundFall( row['Narrative']), axis=1)

這就是我想要實現的:添加一個新列來預測敘述中的失敗。

Year    state   Narrative                                        predicted_failure
------------------------------------------------------------- ---------------------
2015      WV   a roof fall occurred ....... more text....                roof fall
2016      AL   a rib rolled out striking ......more text ....             rib fall
2017      CO   a non-injury mountain ....... more text....                 outburst

我是 Python 的新手,所以希望您能幫我修復代碼以使其正常工作。 高度贊賞實現我目標的更好方法。 先感謝您,

您的 function 未按預期工作。 您想嘗試以下方法:

def predict_groundFall(narrative):
    fall_dict = {'roof fall': ['Roof fall', 'roof broke', 'rock fell from the top'],
                 'rib fall': ['rib fall ', 'rib rolled', 'rib dislodged'],
                 'outburst': ['outburst', 'bounce', 'rockburst']}
    for key in fall_dict:
        if any(v.lower() in narrative.lower() for v in fall_dict[key]):
            return key

然后將您的列分配更改為以下內容:

df['predicted_failure'] = df["Narrative"].apply(lambda x: predict_groundFall(x))

我認為問題出在您的申請 function 中。

更改此行df['predicted_failure'] = df.apply( lambda row: predict_groundFall( row['Narrative']), axis=1)

df['predicted_failure'] = df.Narrative.apply(predict_groundFall)

這會將Narrative的每個值發送到您的自定義 function,然后使用來自該 function 的返回填充新列

暫無
暫無

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

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