我有2个csv文件价格和性能。
这是每个的数据布局
价格:
性能:
我使用以下命令将它们导入python:
import pandas as pd
price = pd.read_csv("cpu.csv")
performance = pd.read_csv("geekbench.csv")
这可以按预期工作,但是我不确定如何创建一个新的csv文件,并在Price [brand + model]和Performance [name]之间进行匹配
我想参加:
使用上面的这些参数创建一个新的csv文件。我一直在寻找一种很好的匹配方法,该方法忽略了细微的差异,例如大写字母。我一直在研究诸如模糊字符串匹配之类的算法,但不确定最佳选择是什么。
这是我当前抛出错误的尝试;
for i in range(len(price.index)):
brand = (price.iloc[i, 0])
model = (price.iloc[i, 1])
print(model)
print(performance)
print(performance.query('name == brand+model'))
谢谢
答案 0 :(得分:2)
我建议以下内容:
import nltk
import pandas as pd
tokenizer = nltk.RegexpTokenizer(r'\w+')
price = pd.DataFrame({"brand": ["AMD", "AMD", "AMD", "AMD"],
"model" : ["2650", "3800", "5150", "4200"],
"cores" : [2,4,4,4],
"tdp" : [25,25,25,25]})
performance = pd.DataFrame({"name": ["AMD Athlon 64 3200+",
"AMD Athlon 64 X2 3800+",
"AMD Athlon 64 X2 4000+",
"AMD Athlon 64 X2 4200+"],
"score" : [6,5,6,18]})
# I break down the name in performance and suppress capital letters
performance["tokens"] = (performance["name"].str.lower()
.apply(tokenizer.tokenize))
# And the same for price
price["tokens"] = price.loc[:,"brand"].values + " " + \
price.loc[:,"model"].values
price["tokens"] = (price["tokens"].str.lower()
.apply(tokenizer.tokenize))
# cartesian product
price["key"] = 1
performance["key"] = 1
df = pd.merge(price,performance, on = "key")
# define my criteria for match
n_match = 2
df['intersection'] =\
[len(list(set(a).intersection(set(b))))
for a, b in zip(df.tokens_x,
df.tokens_y)]
df = df.loc[df["intersection"]>=n_match,:]
我重新定义了您的数据集,以便在本示例中我们将有一些匹配项。结果就是我得到的:
brand model cores ... score tokens_y intersection
5 AMD 3800 4 ... 5 [amd, athlon, 64, x2, 3800] 2
15 AMD 4200 4 ... 18 [amd, athlon, 64, x2, 4200] 2
[2 rows x 10 columns]
您可以为n_match
重新定义条件,我输入了两个,因为看起来这正是数据集所需要的。
希望对您有帮助
答案 1 :(得分:0)
您可以在价格上创建一个“名称”列,然后将其与该名称上的Performane合并,然后合并这两个框架。
Price['name'] = Price.brand + ' ' + Price.model.astype(str)
Price.merge(Performance, on='name')
但是,由于至少您在问题中显示的示例数据行不匹配,因此结果框可能为空。例如,这不是语言问题。大写,但只是缺少信息。只有在您以“真实语言”定义了关系规则之后,您才能使用Python对其进行编码。