List from Column elements

Question:

I want to create a column ‘List’ for column ‘Numbers’ such that it gives a list leaving the element of the corresponding row in pandas.

Table:

| Numbers  | List           |
| -------- | -------------- |
| 1        | [2,3,4,1]      |
| 2        | [3,4,1,1]      |
| 3        | [4,1,1,2]      |
| 4        | [1,1,2,3]      |
| 1        | [1,2,3,4]      |

Can anyone help with this, please?

Asked By: Abhinav Khandelwal

||

Answers:

For general solution working with duplicated values first repeat values by numpy.tile and then remove values of diagonal for delete value of row:

df = pd.DataFrame({'Numbers':[1,2,3,4,1]})

A = np.tile(df['Numbers'], len(df)).reshape(-1, len(df))

#https://stackoverflow.com/a/46736275/2901002
df['new'] = A[~np.eye(A.shape[0],dtype=bool)].reshape(A.shape[0],-1).tolist()
print (df)
0        1  [2, 3, 4, 1]
1        2  [1, 3, 4, 1]
2        3  [1, 2, 4, 1]
3        4  [1, 2, 3, 1]
4        1  [1, 2, 3, 4]
Answered By: jezrael

Try this:

df = pd.DataFrame({'numbers':range(1, 5)})
df['list'] = df['numbers'].apply(lambda x: [i for i in df['numbers'] if i != x])
df
Answered By: Anya Konkina
import pandas as pd

df = pd.DataFrame({'Numbers':[1,2,3,4,5]})

df['List'] = df['Numbers'].apply(
    # for every cell with element x in Numbers return Numbers without the element 
    lambda x: [y for y in df['Numbers'] if not y==x])

which results in:

df
   Numbers          List
0        1  [2, 3, 4, 5]
1        2  [1, 3, 4, 5]
2        3  [1, 2, 4, 5]
3        4  [1, 2, 3, 5]
4        5  [1, 2, 3, 4]
Answered By: Sandwichnick

Abhinar Khandelwal. If the task is to get any other number besides the current row value, than my answer can be fixed to the following:

import numpy as np

rng = np.random.default_rng()
numbers = rng.integers(5, size=7)

df = pd.DataFrame({'numbers':numbers})

df['list'] = df.reset_index()['index'].apply(lambda x: df[df.index != x].numbers.values)

df

But this way is much faster https://stackoverflow.com/a/73275614/18965699 🙂

Answered By: Anya Konkina
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.