首页 > 解决方案 > 检查具有不同值系统的两个数据框列的相似性

问题描述

我有两个不同数据框的两列。以下块是前 5 行,但每列要长得多:

A = pd.DataFrame(['30-34', '20-24', '20-24', '15-19', '00-04'])

B = pd.DataFrame(['6','4', '4', '3', '0'])

我想检查两列是否重合,考虑到

0 represents 00-04; 
1 represents 05-09; 
2 represents 10-14;
3 represents 15-19;
4 represents 20-24;
5 represents 25-29;
and 6 represents 30-34.

所需的输出将是不匹配元素的数量。在给定的示例中,所需的输出为“0”,因为两列的前 5 个值都匹配。我会给出一种我尝试过的方法,但我完全不知道。

标签: pythonpandasdataframe

解决方案


IIUC, you have ranges, 5 by 5, and you want to match them to their integer division.

(B.astype(int).values == A[0].str.split('-', expand=True).astype(int)//5).all(axis=1)

output:

0    True
1    True
2    True
3    True
4    True

Check if the columns coincide:

(B.astype(int).values ==
 A[0].str.split('-', expand=True).astype(int)//5
).all(axis=1).all()

output: True

Intermediate steps:

# split on "-"
>>> A[0].str.split('-', expand=True)
    0   1
0  30  34
1  20  24
2  20  24
3  15  19
4  00  04

# get integer division
>>> A[0].str.split('-', expand=True).astype(int)//5
   0  1
0  6  6
1  4  4
2  4  4
3  3  3
4  0  0

# check if equals B
>>> B.astype(int).values == A[0].str.split('-', expand=True).astype(int)//5
      0     1
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True

推荐阅读