一.遇到的问题描述:
我遇到问题的数据比较复杂,下面以比较简单的数据为例说明问题,所以这些数据的含义是没有意义的,可以忽略数据的的具体意义。数据如下所示:
import numpy as np
import pandas as pd
data = {'city': [{'Beijing':1, 'Shanghai':2,"lanzhou":7}, {'Guangzhou':3, 'Shenzhen':4},{'Hangzhou':5, 'Chongqing':6}],
'word': [["Beijing","Shanghai"],["Guangzhou","Hangzhou"],["Chongqing"]],
'population': [2100, 2300, 1000]}
frame = pd.DataFrame(data, columns = ['word', 'city', 'population'])
frame
我想要统计word的每行数据中每个元素在city的对应行中是否存在,如果存在将对应的字典里面的键值赋给它,并生成一个新的字典。
二.解决方法:
import ast
def get_title_dict(a,b):
title_cut_dict={}
for i in a:
if i in b:
title_cut_dict[i]=b[i]
return title_cut_dict
frame["test"]=frame.apply(lambda x: get_title_dict(x.word, x.city), axis = 1)
frame
结果如下所示:
这个问题还有另外一种处理方式,就是先遍历frame的每行,然后遍历该行中的word,然后遍历city,这样就会有三层循环,速度非常慢。