我很难将用户定义的函数应用于中的特定列。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中。我通过寻找“叙事”中的一些关键词来预测地面塌陷,例如:如果“叙事”包括(以下任何一个单词 ['roof fall', 'roof broke', 'rock fell from the top'] ),那么地面塌陷的预测应该是“屋顶塌陷”。
这是我生成的用户定义函数,但它不起作用。
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的新手,所以我希望您能帮我修复代码,使其正常工作。一个更好的方法来实现我的目标受到高度赞赏。提前谢谢你,
发布于 2021-06-09 21:27:17
您的功能不像预期的那样工作。您想尝试以下几种方法:
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))发布于 2021-06-09 21:30:13
我认为问题在于你的应用功能。
更改这一行df['predicted_failure'] = df.apply( lambda row: predict_groundFall( row['Narrative']), axis=1)
至
df['predicted_failure'] = df.Narrative.apply(predict_groundFall)
这将将Narrative的每个值发送到自定义函数,然后使用该函数的返回填充新列。
https://stackoverflow.com/questions/67911836
复制相似问题