【发布时间】:2021-11-01 15:52:13
【问题描述】:
我已经为我编写了一个函数来从包含在我的数据框中的列中的“值”(在我的字典中定义)中提取“键”。这个问题最好在下面的代码中解释。
我的问题是我的输出列只返回搜索到的最后一个“键”。我想归还所有的钥匙。
不胜感激!
df = pd.DataFrame({'chat':['swimming is great for you! volleyball is fun too.',
'i like to cycle and run during my free time',
'apart from netball, i am good at basketball and diving too']})
sport_dic = {'team': ['basketball', 'soccer','volley','netball','hockey'],
'individual': ['run','swim','cycl','div']}
我的功能:
def type_search(string,dic):
for key,value in dic.items():
return_x = []
for v in value:
if v in string:
return_x.append(key)
return(return_x)
df['chat_type'] = df['chat'].apply(lambda x: type_search(x,sport_dic))
我从我的函数中得到了什么:
df = {'chat': {0: 'swimming is great for you! volleyball is fun too.',
1: 'i like to cycle and run during my free time',
2: 'apart from netball, i am good at basketball and diving too'},
'chat_type': {0: ['team'], 1: ['individual'], 2: ['team']}}
我的期望:
df = {'chat': {0: 'swimming is great for you! volleyball is fun too.',
1: 'i like to cycle and run during my free time',
2: 'apart from netball, i am good at basketball and diving too'},
'chat_type': {0: ['individual','team'], 1: ['individual','individual'], 2: ['team','team','diving']}}
【问题讨论】:
标签: python pandas string dataframe function