在 pandas 数据框的两列中查找常用词,其中包含词表
Find common words in two columns of pandas dataframe consist of list of words
我在 python 中有一个大型 pandas 数据框(大约 100 万行),其中有 2 列由单词列表(Norm1 和 Norm2)组成。
我想用他们共有的词创建一个列(公共)。
| Norm1 | Norm2 |
| ------------------- | -----------------|
| ['apple','inc'] | ['apple'] |
| ['apple','inc'] | ['amazon'] |
| ['apple','inc'] | ['apple','inc'] |
| ['apple','inc'] | ['Tesla'] |
预期列为:
|Common |
|---------------|
|['apple'] |
|[] |
|['apple','inc']|
|[] |
此外,由于数据很大,我想以一种高效的方式进行处理。
感谢您的建议。
df['Common'] = df.apply(lambda x: list(set(x['Norm1']).intersection(set(x['Norm2']))), axis=1)
这会在每列中创建一组值,然后找到交集。
我复制了您的示例输入并创建了一个长度为 150 万行的数据框,运行 只用了大约 25 秒。
我喜欢这类问题,我花了很长时间才找到答案(虽然问题很容易理解)。我的代码是这样的:
import pandas as pd
data = {"Norma": [["apple","inc"], ["apple","inc"], ["apple","inc"], ["apple","inc"]], "Normb": [["apple"], ["amazon"], ["apple","inc"], ["Tesla"]]}
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=data)
df["result"] = df.apply(lambda x: list(set(x['Norma'])&set(x['Normb'])), axis=1)
result
系列中包含您要查找的列表:
Norma Normb result
0 [apple, inc] [apple] [apple]
1 [apple, inc] [amazon] []
2 [apple, inc] [apple, inc] [apple, inc]
3 [apple, inc] [Tesla] []
我在 python 中有一个大型 pandas 数据框(大约 100 万行),其中有 2 列由单词列表(Norm1 和 Norm2)组成。
我想用他们共有的词创建一个列(公共)。
| Norm1 | Norm2 |
| ------------------- | -----------------|
| ['apple','inc'] | ['apple'] |
| ['apple','inc'] | ['amazon'] |
| ['apple','inc'] | ['apple','inc'] |
| ['apple','inc'] | ['Tesla'] |
预期列为:
|Common |
|---------------|
|['apple'] |
|[] |
|['apple','inc']|
|[] |
此外,由于数据很大,我想以一种高效的方式进行处理。 感谢您的建议。
df['Common'] = df.apply(lambda x: list(set(x['Norm1']).intersection(set(x['Norm2']))), axis=1)
这会在每列中创建一组值,然后找到交集。
我复制了您的示例输入并创建了一个长度为 150 万行的数据框,运行 只用了大约 25 秒。
我喜欢这类问题,我花了很长时间才找到答案(虽然问题很容易理解)。我的代码是这样的:
import pandas as pd
data = {"Norma": [["apple","inc"], ["apple","inc"], ["apple","inc"], ["apple","inc"]], "Normb": [["apple"], ["amazon"], ["apple","inc"], ["Tesla"]]}
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=data)
df["result"] = df.apply(lambda x: list(set(x['Norma'])&set(x['Normb'])), axis=1)
result
系列中包含您要查找的列表:
Norma Normb result
0 [apple, inc] [apple] [apple]
1 [apple, inc] [amazon] []
2 [apple, inc] [apple, inc] [apple, inc]
3 [apple, inc] [Tesla] []