1

Given dataframe looking like this:

ID ID_2 Value
12 34 100
12 56 200
12 78 300

How do we:

  1. Filter the dataframe with ID_2 = 34/56/78
  2. Create new columns for each of the Value
ID New column New column_2 New column_3
12 100 200 300
Yuchen
  • 30,852
  • 26
  • 164
  • 234
jsang
  • 11
  • 3
  • 1
    There a several ways to do this. See [link](https://stackoverflow.com/questions/26255671/pandas-column-values-to-columns) – user19077881 Feb 25 '23 at 14:22
  • Does this answer your question? [Pandas column values to columns?](https://stackoverflow.com/questions/26255671/pandas-column-values-to-columns) – Chris Feb 25 '23 at 16:37

1 Answers1

0

You can do it this way:

import pandas as pd

df = pd.DataFrame({'ID': [12, 12, 12], 'ID_2': [34, 56, 78], 'Value': [100, 200, 300]})

df_filtered = df[df['ID_2'].isin([34, 56, 78])]

df_pivot = df_filtered.pivot(index='ID', columns='ID_2', values='Value')
df_pivot.columns = [f"New column_{col}" for col in df_pivot.columns]

df_pivot = df_pivot.reset_index()

print(df_pivot)

which gives

   ID  New column_34  New column_56  New column_78
0  12            100            200            300