0

By using the following dataframe, I would like to create a new column based on a list of other values in my dataframe

import pandas as pd

df1 = pd.DataFrame(
    {
        "A": ["A0", "A1", "A2", "A3"],
        "B": ["B0", "B1", "B2", "B3"],
        "C": ["C0", "C1", "C2", "C3"],
        "D": ["D0", "D1", "D2", "D3"],
    },
    index=[0, 1, 2, 3],
)

The output example I would like to have is the following (Respecting the order is important):

    A   B   C   D  my_group
0  A0  B0  C0  D0  [D0, A0, B0]
1  A1  B1  C1  D1  [D1, A1, B1]
2  A2  B2  C2  D2  [D2, A2, B2]
3  A3  B3  C3  D3  [D3, A3, B3]

I saw some exaples with group by for something similar, but it is not the answer I am looking for: How to group dataframe rows into list in pandas groupby

The Dan
  • 1,408
  • 6
  • 16
  • 41
  • look at the `apply()` method of a pandas dataframe [here](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html). – Ahmed Elashry Jan 06 '22 at 19:12

2 Answers2

2

It's a simple case of creating a list from defined columns

import pandas as pd

df1 = pd.DataFrame(
    {
        "A": ["A0", "A1", "A2", "A3"],
        "B": ["B0", "B1", "B2", "B3"],
        "C": ["C0", "C1", "C2", "C3"],
        "D": ["D0", "D1", "D2", "D3"],
    },
    index=[0, 1, 2, 3],
)

df1["my_group"] = df1.loc[:,["D","A","B"]].apply(list, axis=1)


A B C D my_group
0 A0 B0 C0 D0 ['D0', 'A0', 'B0']
1 A1 B1 C1 D1 ['D1', 'A1', 'B1']
2 A2 B2 C2 D2 ['D2', 'A2', 'B2']
3 A3 B3 C3 D3 ['D3', 'A3', 'B3']
Rob Raymond
  • 29,118
  • 3
  • 14
  • 30
1

Just do tolist

df1['new'] = df1[["D","A","B"]].to_numpy().tolist()
df1
Out[424]: 
    A   B   C   D           new
0  A0  B0  C0  D0  [D0, A0, B0]
1  A1  B1  C1  D1  [D1, A1, B1]
2  A2  B2  C2  D2  [D2, A2, B2]
3  A3  B3  C3  D3  [D3, A3, B3]
BENY
  • 317,841
  • 20
  • 164
  • 234