0

I have a table named df with two columns - Name and Data. The table is something as follows

enter image description here

I am trying to create all possible combinations of values from the Data column and concat the results as separate columns to the existing table. Basically, in every subsequent column, two of the names will take values as 2 and 1.5 and the rest will take the value as 1. I am looking for output as similar to the following table:

enter image description here

Though I have been able to figure out the combination of names that will take the values as 2 and 1.5 in the next column using the following code

for index in list(combinations(df[['Name']].index,2)):
    print(df[['Name']].loc[index,:])
    print('\n')

However, I am stuck on how to create the fresh columns as mentioned above. Any help on the same is highly appreciated.

1 Answer 1

2

I think you are looking for permutations, not combinations. In this case we can generate those and transpose the data. After the transpose we can rename the columns.

import pandas as pd
from itertools import permutations
df = pd.DataFrame({'Name':['A','B','C','D'],
                  'Data':[1,2,1,1.5]})

df = pd.DataFrame(list(permutations(df.Data.values,4)), columns=df.Name.values).T
df.columns = [f'Data{x+1}' for x in df.columns]

df.reset_index(inplace=True)
df.rename(columns={'index':'Name'}, inplace=True)

Or:

pd.DataFrame(list(permutations(df.Data.values,4)), columns=df.Name.values).T.add_prefix('Data').rename_axis('Name').reset_index()

Output

  Name  Data1  Data2  Data3  Data4  Data5  Data6  Data7  Data8  Data9  ...  \
0    A    1.0    1.0    1.0    1.0    1.0    1.0    2.0    2.0    2.0  ...   
1    B    2.0    2.0    1.0    1.0    1.5    1.5    1.0    1.0    1.0  ...   
2    C    1.0    1.5    2.0    1.5    2.0    1.0    1.0    1.5    1.0  ...   
3    D    1.5    1.0    1.5    2.0    1.0    2.0    1.5    1.0    1.5  ...  
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your response. This does the work somewhat, but it is generating duplicate columns for me. Ideally there should have been 12 columns like I have given in the question, but this gives me 24 columns with each column duplicated. Any idea on how to handle that?
There are 24 possible ways to arrange those 4 items, not 12. Permutations will not generate duplicates.
Thank you, I was able to figure out the duplicate issue. Your solution was very helpful :)

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.