'How many times does row from one df have values higher in a row of another df
I have two df frames
df = pd.DataFrame({'1': [0, 0, 0, 0, 0, 0],
'2': [0, 0, 0, 0, 0, 0],
'3': [0, 10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'1': [53, 76, 77, 96, 58, 64],
'2': [42, 61, 65, 74, 45, 54],
'3': [36, 42, 24, 54, 10, 80],})
What I am looking for is a new column in df which states how many times that row has values from df2 in a row which are >= to each number.

Hope I’ve explained it well enough thanks
df = pd.DataFrame({'1': {0: 62, 1: 35, 2: 80, 3: 78, 4: 80, 5: 60, 6: 67, 7: 65, 8: 55, 9: 62},
'2': {0: 52, 1: 28, 2: 43, 3: 57, 4: 60, 5: 37, 6: 32, 7: 23, 8: 33, 9: 38},
'3': {0: 32, 1: 8, 2: 12, 3: 30, 4: 38, 5: 18, 6: 10, 7: 10, 8: 13, 9: 25},
'4': {0: 43, 1: 23, 2: 50, 3: 47, 4: 50, 5: 37, 6: 35, 7: 42, 8: 28, 9: 32},
'5': {0: 62, 1: 45, 2: 55, 3: 75, 4: 62, 5: 63, 6: 43, 7: 58, 8: 55, 9: 72},
'6': {0: 80, 1: 50, 2: 83, 3: 63, 4: 73, 5: 52, 6: 62, 7: 75, 8: 72, 9: 72},
'7': {0: 2, 1: 1, 2: 2, 3: 3, 4: 0, 5: 0, 6: 0, 7: 1, 8: 0, 9: 0}})
df2 = pd.DataFrame({'1': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0},
'2': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0},
'3': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6:0, 7: 0, 8: 0, 9: 0},
'4': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0},
'5': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0},
'6': {0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90},
'7': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}})
Solution 1:[1]
Try with apply:
df["count"] = df.apply(lambda row: row.ge(df2).all(1).sum(), axis=1)
>>> df
1 2 3 4 5 6 7 count
0 62 52 32 43 62 80 2 9
1 35 28 8 23 45 50 1 6
2 80 43 12 50 55 83 2 9
3 78 57 30 47 75 63 3 7
4 80 60 38 50 62 73 0 0
5 60 37 18 37 63 52 0 0
6 67 32 10 35 43 62 0 0
7 65 23 10 42 58 75 1 8
8 55 33 13 28 55 72 0 0
9 62 38 25 32 72 72 0 0
Solution 2:[2]
Try with outer sub
df['count'] = (np.subtract.outer(df2.to_numpy(),df.to_numpy())>=0).all((1,-1)).sum(0)
df
Out[307]:
1 2 3 count
0 0 0 0 6
1 0 0 10 6
2 0 0 20 5
3 0 0 30 4
4 0 0 40 3
5 0 0 50 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | BENY |
