1

I have a pandas DataFrame like so:

import pandas as pd

df = pd.DataFrame({
    'date': ['2001-01-01', '2001-02-01', '2001-01-01', '2001-02-01', '2001-02-01', '2001-03-01'],
    'product': ['A', 'A', 'B', 'B', 'C', 'C'],
    'value': [2.5, 2.6, 1.5, 1.6, 3.2, 3.4]
})

df
    date      product   value
0   2001-01-01   A      2.5
1   2001-02-01   A      2.6
2   2001-01-01   B      1.5
3   2001-02-01   B      1.6
4   2001-02-01   C      3.2
5   2001-03-01   C      3.4

I want to use a for loop to loop over all unique values of product and create separate dataframes with only rows pertaining to that product. The final output I want is below:

A
        date      product   value
    0   2001-01-01   A      2.5
    1   2001-02-01   A      2.6

B
    2   2001-01-01   B      1.5
    3   2001-02-01   B      1.6

C
    4   2001-02-01   C      3.2
    5   2001-03-01   C      3.4
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • It's a bit unclear what your expected output is. You want a dict like `{'A': dataframe_for_product_A, 'B': dataframe_for_product_B, ...}`? – Aran-Fey Mar 27 '18 at 13:45
  • I want separate dataframes, each with name `A`, `B`, and `C`. – Gaurav Bansal Mar 27 '18 at 13:46
  • https://stackoverflow.com/questions/40498463/python-splitting-dataframe-into-multiple-dataframes-based-on-column-values-and – BENY Mar 27 '18 at 13:47
  • So you want to dynamically create variables? I can assure you that you don't really want that. Take a look at [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables). The correct solution is to use a dict instead. – Aran-Fey Mar 27 '18 at 13:48

0 Answers0