繁体   English   中英

比较 Python 数据框中的“类似”列

[英]Compare 'like' columns in Python dataframe

我有两个数据框,它们应该具有相同的数据但来自不同的来源。 我想返回 df1 中的列名以及与 df2 中的等效项进行比较时该列的相应匹配率。

输入:

df1 = 

ID  Age  Value  Name

1   10    1000  Red

2   20    2000  Blue

3   30    3000  Orange

4   40    4000  Grey

df2 =

Age_2  Value_2  Name_2

10    1000  red

20    1500  blue

30    3000  orange

40    4000  white

Desired output:

Name  MatchRate

ID     N/A

Age    1.00

Value  0.75  

Name   0.75

我建议使用difflib.SequenceMatcher来比较字符串,例如以下方式

import difflib
import pandas as pd
def get_ratio(x,y):
    return difflib.SequenceMatcher(None,x,y).ratio()
df = pd.DataFrame({"col1":["Red","Blue","Orange","Grey","White"],"col2":["red","blue","orange","grey","black"]})
df["ratio"] = df.apply(lambda row:get_ratio(row.col1,row.col2),axis=1)
print(df)

给出输出

     col1    col2     ratio
0     Red     red  0.666667
1    Blue    blue  0.750000
2  Orange  orange  0.833333
3    Grey    grey  0.750000
4   White   black  0.000000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM