假设我有df1
:
df1= pd.DataFrame({'alligator_apple': range(1, 11),
'barbadine': range(11, 21),
'capulin_cherry': range(21, 31)})
alligator_apple barbadine capulin_cherry
0 1 11 21
1 2 12 22
2 3 13 23
3 4 14 24
4 5 15 25
5 6 16 26
6 7 17 27
7 8 18 28
8 9 19 29
9 10 20 30
和df2
:
df2= pd.DataFrame({'alligator_apple': [6, 7, 15, 5],
'barbadine': [3, 19, 25, 12],
'capulin_cherry': [1, 9, 15, 27]})
alligator_apple barbadine capulin_cherry
0 6 3 1
1 7 19 9
2 15 25 15
3 5 12 27
我正在寻找一种在df2
中创建一个新列的方法,该列根据以下条件获取行数:df1
中的所有列的值都大于它们在df2
中对应的每一行的值。例如:
alligator_apple barbadine capulin_cherry greater
0 6 3 1 4
1 7 19 9 1
2 15 25 15 0
3 5 12 27 3
更详细地说,在df2
的第0行,df1.alligator_apple
有4行的值高于df2.alligator_apple
的值6df1.barbadine
有10行,其值高于值为3的df2.barbadine
,而类似地df1.capulin_cherry
有10行
最后,将“and”条件应用于上述所有条件,以获得第一行的df2.greater
的数字“4”。对df2
中的其余行重复此操作
有没有一个简单的方法可以做到这一点
我相信这正是你想要的:
输出:
编辑:如果您想对给定的列集概括并应用此逻辑,我们可以将
functools.reduce
与operator.and_
一起使用:有一个通用的解决方案应该可以很好地解决这个问题
输出df2
这将创建一个掩码,遍历给定行的键/值对
编辑这个答案很有帮助:Masking a DataFrame on multiple column conditions - inside a loop
相关问题 更多 >
编程相关推荐