繁体   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