Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

change label in dataframe per condition

import pandas as pd
data = pd.DataFrame({
    'first_name': ['John', 'John', 'Jane', 'Jane', 'Jane','Marry', 'Victoria', 'Gabriel', 'John'],
    'id': [1, 1, 2, 2, 2, 3, 4, 5, 1],
    'age': [30, 30, 25, 25, 25, 30, 45, 15, 30],
    'group': [0, 0, 0, 0, 0, 0, 0, 0, 0],
    'product_type': [1, 1, 2, 1, 2, 1, 2, 1, 2],
    'quantity': [10, 15, 10, 10, 15, 30, 30, 10, 10]
})
data['agemore'] = (data['age'] > 20)

group_val = 0

for id in data['id'].unique():
    age_param = list(set([age_bool for age_bool in data.loc[data['id'] == id, 'agemore']]))
    # Product type removed as per latest requirements
    # product_type_param = list(set([prod_type for prod_type in data.loc[data['id'] == id, 'product_type']]))
    quantity_param = list(set([qty for qty in data.loc[data['id'] == id, 'quantity']]))
            
    if data.loc[(data['id'] == id)
                & (data['group']==0), :].shape[0] > 0:
        group_val += 1

    data.loc[(data['group'] == 0)
         & (data['agemore'].isin(age_param))
         # Product_type removed as per latest requirements
         # & (data['product_type'].isin(product_type_param))
         & (data['quantity'].isin(quantity_param)), 'group'] = group_val
Comment

PREVIOUS NEXT
Code Example
Python :: biopython parse fasta 
Python :: TypeError: strptime() argument 1 must be str, not list 
Python :: 1042 uri solution 
Python :: custom point annotation pyplot scatter 
Python :: how to unpack the whole list without index them individually python 
Python :: Extract column to create new dataframe 
Python :: python matrices access row 
Python :: extract arabic text from image python 
Python :: def print_seconds(hours minutes seconds) print() print_seconds(1 2 3) 
Python :: django Account has no customer 
Python :: custom_settings in scrpay 
Python :: appears in json dump 
Python :: qubesos 
Python :: accessing element from csv file in python 
Python :: how to import qpalette pyqt5 
Python :: hms bagle 
Python :: in python, i am pustin two star before paramerter what is that men 
Python :: Python Script to check how many images are broken 
Python :: networkx - calculate degree per each node 
Python :: username__icontains in django 
Python :: table and amorization charts using tkinter 
Python :: pyspark rdd sort by value descending 
Python :: ciclo while python 
Python :: pygame for loop for draw shape 
Python :: how to download excel file with password from online python 
Python :: tkinter app example code 
Python :: print(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 
Python :: I want only the span of finditer in re python 
Python :: py 
Python :: *args **kwargs together in python 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =