0

I am a new in Python pandas, so sorry if this question is very easy. I have three lists:

A = ['A','B','C']
M = ['1','2','3']
F = ['plus','minus','square']

I want to make those lists combined and show it in data frame. I have tried to use list.append

new_list = []
for i in A:
    new_list.append(i)
    for j in (M):
        new_list.append(j)
print(new_list)
['A', '1', '2', '3', 'B', '1', '2', '3', 'C', '1', '2', '3']

I confused, how to get the output like this (in dataframe):

enter image description here

3
  • 1
    You can use pd.DataFrame(list(product(A,M,F)), columns=['A', 'M', 'F']) Commented Nov 28, 2017 at 6:44
  • what does the meaning of the product in here? Commented Nov 28, 2017 at 6:46
  • you need to import product from itertools like this way: from itertools import product Commented Nov 28, 2017 at 6:47

2 Answers 2

2

It seems as if you want to create all list of all possible permutations. You can do this with itertools and pandas. Itertools is a native library to python:

import pandas as pd
import itertools

A = ['A','B','C']
M = ['1','2','3']
F = ['plus','minus','square']

df = pd.DataFrame(list(itertools.product(A,M,F)), columns=['A','M','F'])
print(df)

Output:

    A  M       F
0   A  1    plus
1   A  1   minus
2   A  1  square
3   A  2    plus
4   A  2   minus
5   A  2  square
6   A  3    plus
7   A  3   minus
8   A  3  square
9   B  1    plus
10  B  1   minus
11  B  1  square
12  B  2    plus
13  B  2   minus
14  B  2  square
15  B  3    plus
16  B  3   minus
17  B  3  square
18  C  1    plus
19  C  1   minus
20  C  1  square
21  C  2    plus
22  C  2   minus
23  C  2  square
24  C  3    plus
25  C  3   minus
26  C  3  square
Sign up to request clarification or add additional context in comments.

Comments

1

What you need is a Cartesian product of the three sets:

import pandas as pd
from itertools import product

pd.DataFrame(list(product(A,M,F)), columns=['A', 'M', 'F'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.