有一个数据框exex为 是否有更高效的pandas方法将现有数据帧df的值更新为值exex.EXEX ,其中exex.I字段是索引, exex.J字段是列? 有没有办法通过指定名称而不是行索引来更新数据? 这是因为如果名称字段发生变化,则行索引会有所不同,并可能导致错误的结果。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我正在尝试在其标题列上合并两个关于电影的数据框。 不幸的是,它们不共享索引,排序不同,并且不包含所有相同的电影。 我已经对标题进行了足够的清理,以至于我可以比较它们并确定它们是否可以接受地相似以被称为同一部电影。 在比较之后,我试图将那些“匹配”的标题设置为彼此相等(从 df2 中获取标题并覆盖它在 df 中的等价物),但我似乎无法让它工作。
这是 df.head(10)
Unnamed: 0 title imdb_id \
72 72 Gully Boy tt2395469
767 767 Long Shot tt2139881
1000 1000 Little tt8085790
1285 1285 Dumbo tt3861390
1342 1342 Don"t Stop Me Now tt9260446
1358 1358 How to Train Your Dragon: The Hidden World tt2386490
1621 1621 Captive State tt5968394
1658 1658 Spider-Man: Far from Home tt6320628
1944 1944 Avengers: Endgame tt4154796
1946 1946 Captain Marvel tt4154664
这是 df2.head(10)
Unnamed: 0 bo_year_rank title \
7455 0 1 Avengers Endgame
7456 1 2 The Lion King
7457 2 3 Captain Marvel
7458 3 4 Spider-Man Far from Home
7459 4 5 Toy Story 4
7460 5 6 Aladdin
7461 6 7 Fast Furious Presents Hobbs Shaw
7462 7 8 The Wandering Earth
7463 8 9 Ne Zha
7464 9 10 How to Train Your Dragon The Hidden World
我正在使用的比较 function:
def fix_stupid_titles(title, list_titles, min_score=0):
# -1 score incase we don't get any matches
max_score = -1
# Returning empty name for no match as well
max_title = ""
# Iterating over all names in the other
for title2 in list_titles:
#Finding fuzzy match score
score = fuzz.ratio(title, title2)
# Checking if we are above our threshold and have a better score
if (score > min_score) & (score > max_score):
max_title = title2
max_score = score
return (title, max_title, max_score)
我的想法是遍历一个 dataframe 并应用愚蠢的标题 function 来检查相似性,但是我不确定如何更新标题以使它们相等。
for i, title in enumerate(df.title):
thing=fix_stupid_titles(title, df2.title, min_score=75)
#thing saves the return of the functoin (title, max_title, score)
df['title'][thing[1]]=thing[0]
当 function 确定它们相似时,我希望df
中的标题被df2
中的标题覆盖。
任何帮助,将不胜感激。 或有关如何更有效地解决此问题的 go 的建议。 谢谢!
您可以通过fuzzywuzzy 的process
简单地实现它。
df_choices = df['title'].values
这将从您的df
Dataframe 获取标题列表
def fuzzratio(row, options):
match, score = process.extractOne(row['title'], options, scorer=fuzz.ratio)
row['matches'] = match
row['score'] = score
return row
matches = df2.apply(lambda x: fuzzratio(x, df_choices), axis=1)
matches.columns = ['title', 'matches', 'score']
function fuzzratio
用于获得df2
Dataframe 中所有标题的最佳匹配标题。
merges = df2.merge(matches, on='title', how = 'inner')
merges = merges.loc[merges['score'] >= 90]
merges.drop('score', axis=1, inplace=True)
merges.columns = ['new_title', 'title']
过滤所有得分大于 75 的标题。
df = df.merge(merges, on='title', how = 'left')
df.loc[~df['new_title'].isna(), 'title'] = df['new_title']
df.drop('new_title', axis=1, inplace=True)
将原始df
与来自merges
dataframe 的标题合并。 合并后,覆盖标题。
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.