两个列表中所有可能组合的Pandas数据框架

3

如何用最佳方式获得两个列表中所有可能组合的数值,在pandas dataframe中提供两列?

我已经使用itertools获取了一个包含组合的列表,但无法弄清如何将其放入dataframe中。

以下是我的尝试:

import itertools
import pandas as pd

income_range = np.linspace(1,3,3)
costs_range = np.linspace(1, 3, 3)
all_combinations = [list(zip(each_permutation, costs_range)) for each_permutation in itertools.permutations(income_range, len(costs_range))]
df = pd.DataFrame(all_combinations)

这是我得到的输出结果。
|    | 0          | 1          | 2          |
|---:|:-----------|:-----------|:-----------|
|  0 | (1.0, 1.0) | (2.0, 2.0) | (3.0, 3.0) |
|  1 | (1.0, 1.0) | (3.0, 2.0) | (2.0, 3.0) |
|  2 | (2.0, 1.0) | (1.0, 2.0) | (3.0, 3.0) |
|  3 | (2.0, 1.0) | (3.0, 2.0) | (1.0, 3.0) |
|  4 | (3.0, 1.0) | (1.0, 2.0) | (2.0, 3.0) |
|  5 | (3.0, 1.0) | (2.0, 2.0) | (1.0, 3.0) |

这是我想要的输出结果

| Income | Costs |
| ------ | ----- |
| 1      | 1     |
| 1      | 2     |
| 1      | 3     |
| 2      | 1     |
| 2      | 2     |
| 2      | 3     |
| 3      | 1     |
| 3      | 2     |
| 3      | 3     |
2个回答

3

在这里使用 itertools.product:

income_range = np.linspace(1,3,3)
costs_range = np.linspace(1, 3, 3)

all_combinations = list(itertools.product(income_range, costs_range))
df = pd.DataFrame(all_combinations, columns=['Income','Costs'])
print (df)
   Income  Costs
0     1.0    1.0
1     1.0    2.0
2     1.0    3.0
3     2.0    1.0
4     2.0    2.0
5     2.0    3.0
6     3.0    1.0
7     3.0    2.0
8     3.0    3.0

1
你可以使用Meshgrid来解决这个问题:
result = np.reshape(np.vstack(np.meshgrid(income_range, costs_range)), (-1, 2))
pd.DataFrame(result)

    0   1
0   1.0 2.0
1   3.0 1.0
2   2.0 3.0
3   1.0 2.0
4   3.0 1.0
5   1.0 1.0
6   2.0 2.0
7   2.0 3.0
8   3.0 3.0

你可以在这里查看可能的优化。请注意,这在处理数字方面表现出色;对于其他数据类型,特别是字符串,我认为itertools的product函数很适合(@jezrael的解决方案)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接