mercredi 7 août 2019

Return df using if statement [duplicate]

This question already has an answer here:

I am hoping to create and return a subsetted df using an if statement. Specifically, for the code below, I have two lists which contain different values. The df I want to return will vary based on the value within these two lists. Using the code below, the two lists are normal and different. The value in place will dictate how the df will be subsetted.

Below is my attempt. The value in place will only ever be a single value, so it won't match the lists in full. Is it possible to to return the df when the value in place is equal to a single value with these lists? The current output I'm getting is from the else statement. I'm hoping to return df1 to be used for subsequent tasks.

import pandas as pd

df = pd.DataFrame({
    'period' : [1.0, 1.0, 2.0, 2.0, 3.0, 4.0, 5.0, 7.0, 7.0, 8.0, 9.0],                                
    })

place = ['a']

normal = ['a','b']
different = ['v','w','x','y','z']

different_item = 2
normal_item = 4
end = 8

if place == different:
    print('place is different')
    df1 = df[(df['period'] >= different_item) & (df['period'] <= end)].drop_duplicates(subset = 'period')
elif place == normal:
    print('place is normal')
    df1 = df[(df['period'] >= normal_item) & (df['period'] <= end)].drop_duplicates(subset = 'period')
else:
    print('Incorrect input for place. Please check value')

Intended output would be to return df1 to be used later.

   period
2     2.0
4     3.0
5     4.0
6     5.0
7     7.0
9     8.0

Aucun commentaire:

Enregistrer un commentaire