我有一个如下所示的数据框:
Price
-2000
-1750
-1200
-1000
-500
0
500
1000
1200
1750
2000
对我来说,了解哪些行具有相同的值(按绝对值计算)或哪些行组合加起来为零(例如 -1200 + 1200 = 0,这样这将是一个成功的组合)非常重要。
我在比较同一列中的多行时总是遇到问题,所以我想你也许可以帮助我!预先非常感谢。
Ps:快速感谢您对这个社区对学习和新手的大力支持。你们在开发编码知识方面可能比其他任何地方都做得更多!
最佳答案
使用groupby
怎么样
df['abs_price'] = df['Price'].apply(abs)
gp = df.groupby('abs_price')
gp.groups
输出:
{0: Int64Index([5], dtype='int64'),
500: Int64Index([4, 6], dtype='int64'),
1000: Int64Index([3, 7], dtype='int64'),
1200: Int64Index([2, 8], dtype='int64'),
1750: Int64Index([1, 9], dtype='int64'),
2000: Int64Index([0, 10], dtype='int64')}
扩展一下,如果您不想将两个正数组合在一起,您可以很容易地找到所有加起来为 0 的对或行:
import itertools
zero_combinations = []
for index_combo in itertools.combinations(df.index, 2):
if df.iloc[list(index_combo),]['price'].sum() == 0:
zero_combinations.append(index_combo)
print(zero_combinations)
Out: [(0, 10), (1, 9), (2, 8), (3, 7), (4, 6)]
关于python - 如何告诉 Python 合并列中的每一行并返回加起来为零的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57163845/