【问题标题】:Multiplying a list of (X, Y) combinations将 (X, Y) 组合的列表相乘
【发布时间】:2019-05-14 18:17:11
【问题描述】:

我正在尝试将我生成的组合相乘并从中创建一个新列表。

这是我目前所拥有的:

import pandas as pd
import itertools

data1 = [[0.1],[0.2],[0.3],[0.5]]

df = pd.DataFrame(data1, columns = ['weights'])

for x in combinations(df['weights'], 2):
    print(x)

>>>
(0.1, 0.2)
(0.1, 0.3)
(0.1, 0.5)
(0.2, 0.3)
(0.2, 0.5)
(0.3, 0.5)
##I want to make a new list that shows the product of each combinations,
## example: for every (x,y) combo, do x*y and make a new list called z

预期的输出应该产生一个新的列表:

0.02
0.03
0.05
0.06
0.1
0.15

【问题讨论】:

标签: python combinations itertools multiplication


【解决方案1】:

你可以用一个简单的列表理解来做到这一点,你不必使用itertools

inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]

z = [round(elem[0]*elem[1],2) for elem in inlist]
print(z)

输出:

[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

但是,如果你想使用itertools,你可以使用starmap 函数:

from itertools import starmap
inlist = [(0.1, 0.2),
(0.1, 0.3),
(0.1, 0.5),
(0.2, 0.3),
(0.2, 0.5),
(0.3, 0.5)]

z = list(starmap(lambda i,j: round(i*j,2), inlist))
print(z)

输出:

[0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

【讨论】:

  • 谢谢!如果我使用 Excel 工作表中的列中的数据怎么办。我可以输入 inlist = [df['Weights']] 吗?
  • @EmilyRamirez 我不熟悉pandas。您可以尝试并使用结果更新您的问题。
【解决方案2】:

您可以使用任何可迭代对象来进行这些组合。

如果您是 Python 新手,此答案试图阐明一些选项。

给定

一个reducing函数mul和一个可迭代的数据:

def mul(a, b):                                         # 1
    """Return a rounded multiple."""
    return round(a * b, 2)                             


data = [0.1, 0.2, 0.3, 0.5]                            # 2

代码

准备一个可迭代的 - 一个可以循环的线性容器。例子:

选项 1 - 一个迭代器

iterable = it.combinations(data, 2)

选项 2 - pandas DataFrame

df = pd.DataFrame(data, columns=["weights"])
iterable = it.combinations(df["weights"], 2)

演示

[mul(x, y) for x, y in iterable]                      # 3
# [0.02, 0.03, 0.05, 0.06, 0.1, 0.15] 

详情

  1. 此函数包含您要应用的操作。
  2. 一个简单的可迭代数据(例如list)。请注意,它不需要嵌套。
  3. 使用任何可迭代对象来减少组合对

选项 3 - 熊猫操作

或者,一旦你在 pandas 中获得数据,你就可以坚持下去:

combs = list(it.combinations(data, 2))
df = pd.DataFrame(combs, columns=["a", "b"])
df
#      a    b
# 0  0.1  0.2
# 1  0.1  0.3
# 2  0.1  0.5
# 3  0.2  0.3
# 4  0.2  0.5
# 5  0.3  0.5

df.prod(axis=1).round(2).tolist()
# [0.02, 0.03, 0.05, 0.06, 0.1, 0.15]

我建议选择纯 Python 或 pandas(选项 1 或 3)。

【讨论】:

  • 谢谢 pylang。这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多