Putting rows of pandas dataframe into list form

Viewed 73

I have a pandas dataframe of the form

    T1  T2
0   A   B
1   C   D
2   B   C
3   D   E
4   F   A

I would like to generate another pandas dataframe that lists each of the unique items in T1 and T2 has its own row, and has a column with the name of that unique item and a column with a list of the items it shared a row with in the original dataframe. For example, in this case I would be looking for something of the form:

    Name    List
0   A   [B, F]
1   B   [A, C]
2   C   [D, B]
3   D   [C, E]
4   E   [D]
5   F   [A]

Can someone suggest a proper pandonic (like pythonic but for pandas :)) way to do this? Thanks in advance!

1 Answers

IIUC, swap columns and use pandas.DataFrame.columns:

df2 = df.copy()
df2.columns = df.columns[::-1]
new_df = pd.concat([df, df2])
new_df.groupby("T1")["T2"].apply(list).reset_index()

Output:

  T1      T2
0  A  [B, F]
1  B  [C, A]
2  C  [D, B]
3  D  [E, C]
4  E     [D]
5  F     [A]
Related