renan
renan

Reputation: 130

Stack some columns of dataframe

My pandas dataframe is something like this table/image below:

product_id  product_name  package_mod  price  package_50g  price_50g  package_100g  price_100g
2017210     potato        1KG          3.39   50g          0.1695     100g          0.339
2017081     onion         1KG          3.59   50g          0.1795     100g          0.359
2017217     lemon         1KG          2.79   50g          0.1395     100g          0.279

ORIGINAL DF

I want this output, an append through product_id series.

enter image description here

I tried almost anything, like pd.merge, pd.melt, pd.append etc.

I know that I can do it manually, by merging each product_id one by one, but I have several columns like these, so I think it's not an option.

Upvotes: 0

Views: 93

Answers (1)

Corralien
Corralien

Reputation: 120459

You are looking to pd.wide_to_long:

out = pd.wide_to_long(df.rename(columns={'price': 'price_mod'}),
                      stubnames=['package', 'price'],
                      i=['product_id', 'product_name'],
                      j='dummy', sep='_', suffix=r'\w+') \
        .droplevel(level='dummy').reset_index()

Output:

>>> out
   product_id product_name package   price
0     2017210       potato     1KG  3.3900
1     2017210       potato     50g  0.1695
2     2017210       potato    100g  0.3390
3     2017081        onion     1KG  3.5900
4     2017081        onion     50g  0.1795
5     2017081        onion    100g  0.3590
6     2017217        lemon     1KG  2.7900
7     2017217        lemon     50g  0.1395
8     2017217        lemon    100g  0.2790

Upvotes: 3

Related Questions