0

I have a pandas dataframe that contains two columns, one columns has many values and the other column only contains values most of which are same. This is what the dataframe looks like:

Item        Price

Apple        10
Banana        5
Mango        10 
Pineapple     7 
Kiwi          5
Tomatoes      2 
Eggs         10
Potatoes      7
Burgers       5
Milk          2
Chicken      10
Coffee        7
Noodles       5

The values on the price column change. I want to be be able to filter the items for which the prices are same and create a new dataframe from them. What I'm not being able to do is the look for different prices which occur, if the prices were to stay the same then I am able to filter the items based on that but I can't when the prices arbitrarily change. This is what I want to achieve, it is only a dataframe for one particular price as an example.

Item       Price

Apple        10
Mango        10
Eggs         10
Chicken      10
Faisal Afzal
  • 255
  • 1
  • 11

2 Answers2

1

You can use dataframe function for getting the subset.

price_list = df.Price.unique()
sets = []
for price in price_list:
    sets.append(df[df.Price == price])
Johny Jose
  • 11
  • 4
  • I know this already, the problem is that I don't know the prices of the newer dataframes in which they change arbitrary. I can only use this if I know which are the prices that exist in the dataframe which is quite large and to pin point each price is humanly impossible – Faisal Afzal Jan 28 '19 at 11:21
  • Sorry for the confusion, you could get unique values of price at any given point `df.Price.unique()` and then use that list to obtain the seperate new dataframes – Johny Jose Jan 28 '19 at 11:23
1

You can do this using below:

df_new = []
for i in df['Price'].unique():
    df1 = df[df['Price']==i]
    df_new.append(df1)

print(df_new[0])

Output:

Item       Price

Apple        10
Mango        10
Eggs         10
Chicken      10
Sociopath
  • 13,068
  • 19
  • 47
  • 75