Pandas Dataframe: create new label columns based on other columns

I have this example pandas.DataFrame

with + 20K lines, in the following form:

import pandas as pd
import numpy as np

data = {"first_column": ["A", "B", "B", "B", "C", "A", "A", "A", "D", "B", "A", "A"],
        "second_column": [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]}

df = pd.DataFrame(data)

>>> df
   first_column  second_column
0             A              0
1             B              1
2             B              1
3             B              1
4             C              0
5             A              0
6             A              0
7             A              1
8             D              1
9             B              1
10            A              1
11            A              0
....

      

The column first_column

has for each row A

, B

, C

and D

. The second column contains a binary label that represents a group of values. All consecutive groups of 1 are a unique "group", for example. lines 1-3 are one group, lines 7-10 are another group.

I would like to "label" each of these groups by being either "AB" (the group consists of only A or B), "CD" (the group consists of only C or D), or "mixed" (if there is a mixture, for example, all B and one C). It would also be useful to know "how" some of these groupings are mixed, ie. Percentage AB of total labels. So, if it's only A

or B

, then the identifier should be AB

. If it is only C

or D

, then the identifier must be CD

. It's a mixture of A, B, C and / or D, then she is mixed

. Percentage (# of AB lines) / (# of all lines)

This is what the result would look like DataFrame

:

>>> df
   first_column  second_column    identity    percent
0             A              0           0          0
1             B              1          AB        1.0
2             B              1          AB        1.0
3             B              1          AB        1.0
4             C              0           0          0
5             A              0           0          0
6             A              0           0          0
7             A              1       mixed       0.75  # 3/4, 3-AB, 4-total
8             D              1       mixed       0.75
9             B              1       mixed       0.75
10            A              1       mixed       0.75
11            A              0           0          0 
....

      

My initial thought was to first try to use df.loc()

with

if (df.first_column == "A" | df.first_column == "B"):
    df.loc[df.second_column == 1, "identity"] = "AB"
if (df.first_column == "C" | df.first_column == "D"):
    df.loc[df.second_column == 1, "identity"] = "CD"

      

but this does not account for mixtures and does not work with isolated groups.

+3


source to share


2 answers


Here's one way to do it.

Code:

import pandas as pd

from collections import Counter
a_b = set('AB')
c_d = set('CD')

def get_id_percent(group):
    present = Counter(group['first_column'])
    present_set = set(present.keys())

    if group['second_column'].iloc[0] == 0:
        ret_val = 0, 0
    elif present_set.issubset(a_b) and len(present_set) == 1:
        ret_val = 'AB', 0
    elif present_set.issubset(c_d) and len(present_set) == 1:
        ret_val = 'CD', 0
    else:
        ret_val = 'mixed', \
               float(present['A'] + present['B']) / len(group)

    return pd.DataFrame(
        [ret_val] * len(group), columns=['identity', 'percent'])

      

Test code:



data = {"first_column": ["A", "B", "B", "B", "C", "A", "A",
                         "A", "D", "B", "A", "A"],
        "second_column": [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]}

df = pd.DataFrame(data)

groupby = df.groupby((df.second_column != df.second_column.shift()).cumsum())

results = groupby.apply(get_id_percent).reset_index()
results = results.drop(['second_column', 'level_1'], axis=1)
df = pd.concat([df, results], axis=1)
print(df)

      

Results:

   first_column  second_column identity  percent
0             A              0        0     0.00
1             B              1       AB     0.00
2             B              1       AB     0.00
3             B              1       AB     0.00
4             C              0        0     0.00
5             A              0        0     0.00
6             A              0        0     0.00
7             A              1    mixed     0.75
8             D              1    mixed     0.75
9             B              1    mixed     0.75
10            A              1    mixed     0.75
11            A              0        0     0.00

      

+4


source


Here's one approach:

import pandas as pd

# generate example data
data = {"first_column": ["A", "B", "B", "B", "C", "A", "A", "A", "D", "B", "A", "A"],
    "second_column": [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]}
df = pd.DataFrame(data)

# these are intermediary groups for computation
df['group_type'] = None
df['ct'] = 0

def find_border(x, ct):
    ''' finds and labels lettered groups ''' 
    ix = x.name
    # does second_column == 1?
    if x.second_column:
        # if it the start of a group...
        if (not ix) | (not df.group_type[ix-1]):
            df.ix[ix,'group_type'] = x.first_column
            df.ix[ix,'ct'] += 1
            return
        # if it the end of a group
        elif (not df.second_column[ix+1]):
                df.ix[ix,'group_type'] = df.group_type[ix-1] + x.first_column
                df.ix[ix,'ct'] = df.ct[ix-1] + 1
                for i in range(df.ct[ix-1]+1):
                    df.ix[ix-i,'group_type'] = df.ix[ix,'group_type']
                df.ix[ix,'ct'] = 0
                return
        # if it the middle of a group
        else:
            df.ix[ix,'ct'] = df.ct[ix-1] + 1
            df.ix[ix,'group_type'] = df.group_type[ix-1] + x.first_column
            return
    return

# compute group membership
_=df.apply(find_border, axis='columns', args=(0,))

def determine_id(x):
    if not x:
        return '0'
    if list(set(x)) in [['A'],['B'],['A','B']]:
        return 'AB'
    elif list(set(x)) in [['C'],['D'],['C','D']]:
        return 'CD'
    else:
        return 'mixed'

def determine_pct(x):
    if not x:
        return 0
    return sum([1 for letter in x if letter in ['A','B']]) / float(len(x))

# determine row identity
df['identity'] = df.group_type.apply(determine_id)

# determine % of A or B in group
df['percent'] = df.group_type.apply(determine_pct)

      



Output:

   first_column  second_column identity  percent
0             A              0        0     0.00
1             B              1       AB     1.00
2             B              1       AB     1.00
3             B              1       AB     1.00
4             C              0        0     0.00
5             A              0        0     0.00
6             A              0        0     0.00
7             A              1    mixed     0.75
8             D              1    mixed     0.75
9             B              1    mixed     0.75
10            A              1    mixed     0.75    
11            A              0        0     0.00

      

+1


source







All Articles