gpt4 book ai didi

python - 如何使用 .apply 和用户定义函数在 pandas df 中创建列

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:05 25 4
gpt4 key购买 nike

我正在尝试一次在 pandas DataFrame 中创建多个列,其中每个列名都是字典中的一个键,如果存在与该键对应的任何值,则该函数返回 1。

我的 DataFrame 有 3 列,jp_ref、jp_title 和 jp_description。本质上,我在 jp_descriptions 中搜索分配给该键的相关词,并根据是否在 jp_description 中找到任何值,用 1 和 0 填充分配给该键的列。


jp_tile = [‘software developer’, ‘operations analyst’, ‘it project manager’]

jp_ref = [‘j01’, ‘j02’, ‘j03’]

jp_description = [‘software developer with java and sql experience’, ‘operations analyst with ms in operations research, statistics or related field. sql experience desired.’, ‘it project manager with javascript working knowledge’]

myDict = {‘jp_title’:jp_title, ‘jp_ref’:jp_ref, ‘jp_description’:jp_description}

data = pd.DataFrame(myDict)

technologies = {'java':['java','jdbc','jms','jconsole','jprobe','jax','jax-rs','kotlin','jdk'],
'javascript':['javascript','js','node','node.js','mustache.js','handlebar.js','express','angular'
'angular.js','react.js','angularjs','jquery','backbone.js','d3'],
'sql':['sql','mysql','sqlite','t-sql','postgre','postgresql','db','etl']}

def term_search(doc,tech):
for term in technologies[tech]:
if term in doc:
return 1
else:
return 0

for tech in technologies:
data[tech] = data.apply(term_search(data['jp_description'],tech))

我收到以下错误,但不明白:

TypeError: ("'int' object is not callable", 'occurred at index jp_ref')

最佳答案

您的逻辑错误,您在循环中遍历列表,在第一次迭代后返回 0 或 1,因此永远不会将 jp_description 值与完整列表进行比较。

您拆分 jp_description 并使用技术字典检查公共(public)元素,如果存在公共(public)元素,则意味着找到子字符串,因此返回 1 否则返回 0

def term_search(doc,tech):
doc = doc.split(" ")
common_elem = list(set(doc).intersection(technologies[tech]))
if len(common_elem)>0:
return 1
return 0

for tech in technologies:
data[tech] = data['jp_description'].apply(lambda x : term_search(x,tech))
     jp_title          jp_ref  jp_description   java    javascript  sql
0 software developer j01 software developer.... 1 0 1
1 operations analyst j02 operations analyst .. 0 0 1
2 it project manager j03 it project manager... 0 1 0

关于python - 如何使用 .apply 和用户定义函数在 pandas df 中创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com