Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List from Column elements

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading