我有两个数据帧df1,df2。 df1 ['A']保存一个单词列表。 df2 ['b']包含几个单词。我需要有一个单独的df3,我需要说出df1 ['A']中有df ['b']个词。
我是python的新手,我拥有的解决方案是一个非常不雅致的“ for循环”,其中,我遍历df1 ['A']的单词,并遍历df2 ['b']的单词,然后检查并设置一个计数。 我相信有更好,更快的方法来实现这一目标。谁能指出我正确的方向? ****更新**** 很抱歉这个不清楚的问题。以下是我要实现的目标的表示。 data
非常感谢您的帮助。
答案 0 :(得分:0)
我认为为了您的利益,您应该开始研究函数调用。尽管它们与正在处理的数据量成比例地扩展,但是在您的情况下,性能可能微不足道。
'''
Create a dataframe from the cartesian product of two other dataframes:
df1 = pd.DataFrame({'a': [['red apples', 'ripe oranges'],
['ripe mangoes', 'unripe pineapple']]})
df2 = pd.DataFrame({'b': ['apples, mangoes', 'grapes, mangoes, pineapple']})
p = [[x[0], y[0]] for x,y in product(df1.values.tolist(), df2.values.tolist())]
df = pd.DataFrame(p)
'''
def get_counts(row):
return sum(1 for item in row[1].split(', ') for thing in row[0] if item in thing)
df['count'] = df.apply(get_counts, axis=1)
print(df)
您也可以这样做:
df[1] = df[1].str.split(', ').apply(set)
df[0] = df[0].str.join(' ').str.split()
df['count'] = df.apply(lambda x: x[1].intersection(x[0]), axis=1).apply(len)
如果您只想计数,
#As series:
df = df['count']
#As dataframe:
df = df[['count']]