gpt4 book ai didi

python - Pandas :将一列与数据框的所有其他列进行比较

转载 作者:行者123 更新时间:2023-11-28 18:28:10 24 4
gpt4 key购买 nike

我有一个场景,我对新主题进行了一系列特征测试,结果都是字符串分类值。测试完成后,我需要将新数据集与所有主题的主数据集进行比较,并寻找给定阈值保持(比如 90%)的相似性(匹配)。

因此,我需要能够对新数据集中的每个新主题与主数据集中的每一列以及新数据集中的其他列进行列式(按主题)比较可能的最佳性能,因为生产数据集有大约 50 万列(并且还在增加)和 10,000 行。

下面是一些示例代码:

master = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'], 
'S1':['AA','BB','AB'],
'S2':['AB','-','BB'],
'S3':['AA','AB','--']})
new = pd.DataFrame({'Characteristic':['C1', 'C2', 'C3'],
'S4':['AA','BB','AA'],
'S5':['AB','-','BB']})
new_master = pd.merge(master, new, on='Characteristic', how='inner')

def doComparison(comparison_df, new_columns, master_columns):
summary_dict = {}
row_cnt = comparison_df.shape[0]

for new_col_idx, new_col in enumerate(new_columns):
# don't compare the Characteristic column
if new_col != 'Characteristic':
print 'Evalating subject ' + new_col + ' for matches'
summary_dict[new_col] = []
new_data = comparison_df.ix[:, new_col]
for master_col_idx, master_col in enumerate(master_columns):
# don't compare same subject or Characteristic column
if new_col != master_col and master_col != 'Characteristic':
master_data = comparison_df.ix[:, master_col]
is_same = (new_data == master_data) & (new_data != '--') & (master_data != '--')
pct_same = sum(is_same) * 100 / row_cnt
if pct_same > 90:
print ' Found potential match ' + master_col + ' ' + str(pct_same) + ' pct'
summary_dict[new_col].append({'match' : master_col, 'pct' : pct_same})
return summary_dict

result = doComparison(new_master, new.columns, master.columns)

这种方式可行,但我想提高效率和性能,但不知 Prop 体怎么做。

最佳答案

另一种选择

import numpy as np
import pandas as pd
from sklearn.utils.extmath import cartesian

利用 sklearn 的笛卡尔函数

col_combos = cartesian([ new.columns[1:], master.columns[1:]])
print (col_combos)

[['S4' 'S1']
['S4' 'S2']
['S4' 'S3']
['S5' 'S1']
['S5' 'S2']
['S5' 'S3']]

为 new 中除 Characteristic 之外的每一列创建一个带有键的字典。请注意,这似乎是在浪费空间。也许只保存那些有火柴的?

summary_dict = {c:[] for c in new.columns[1:]} #copied from @Parfait's answer

Pandas/Numpy 可以轻松比较两个系列。
示例;

print (new_master['S4'] == new_master['S1'])

0 True
1 True
2 False
dtype: bool

现在我们在 numpy 的 count_nonzero() 的帮助下遍历系列组合并计算真值。其余的与您所拥有的相似

for combo in col_combos:
match_count = np.count_nonzero(new_master[combo[0]] == new_master[combo[1]])
pct_same = match_count * 100 / len(new_master)
if pct_same > 90:
summary_dict[combo[0]].append({'match' : combo[1], 'pct': match_count / len(new_master)})

print (summary_dict)

{'S4': [], 'S5': [{'pct': 1.0, 'match': 'S2'}]}

我很想知道它的表现如何。祝你好运!

关于python - Pandas :将一列与数据框的所有其他列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647269/

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