I want to split a DataFrame into 2 df's using lambda on a column

Viewed 50

I got the following pandas DataFrame:

Value1 Value2 Food
-2 2 Apple
5 -5 Orange
-4 3 Peach
-2 6 Pineapple

I'm now trying to split up the rows into 2 Dataframes based on the 'Value1' Value. So that the outcome would look like this:

NegativeValue1:

Value1 Value2 Food
-2 2 Apple
-4 3 Peach
-2 6 Pineapple

NegativeValue2:

Value1 Value2 Food
5 -5 Orange

I've used a for loop combined with an if statement so far:

for i in range(len(data)):
        if data['Value1'].iloc[i] < 0:
            NegativeValue1 = NegativeValue1.append(data.iloc[i])
        else:
            NegativeValue2 = NegativeValue2.append(data.iloc[i])

, which does work well, but is too time-intensive for large df's.

Because of this I want to build a lambda function to do this, but I don't have much experience with lambda.

My attempts so far were unsuccessful:

NegativeValue1 = NegativeValue1.apply(lambda data:  if data['Value1']  < 0, axis = 1)

Can anyone help?

2 Answers

You can use boolean indexing (both simpler and faster than apply):

NegativeValue1 = data[data.Value1 < 0]

#    Value1  Value2       Food
# 0      -2       2      Apple
# 2      -4       3      Peach
# 3      -2       6  Pineapple
NegativeValue2 = data[data.Value2 < 0]

#    Value1  Value2       Food
# 1       5      -5     Orange

You can use boolean indexing:

mask = df["Value1"] < 0

print(df[mask])
print("-" * 80)
print(df[~mask])

Prints:

   Value1  Value2       Food
0      -2       2      Apple
2      -4       3      Peach
3      -2       6  Pineapple
--------------------------------------------------------------------------------
   Value1  Value2    Food
1       5      -5  Orange
Related