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
CodePudding user response:
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'] |
CodePudding user response:
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]
