How to rename elements of a column based on condit

2019-05-15 09:51发布

问题:

In pandas, given this data frame:

df = pd.DataFrame({'l':['a','b','a','c','b','b','a','b','b','a'], 'v':['x','x','y','y','y','x','x','y','x','y'],'n':[1,2,1,2,2,1,2,1,1,2], 'g':[0,0,0,0,0,1,1,1,1,1]})

What is the best solution to rename the elements of v based on some conditional statements applied to the data frame?

Basically, for each row (regardless of whether g == 0 or g == 1):

if df.l==a and df.n==1:
    df.v='val1'
elif df.l==a and df.n==2:
    df.v='val2'
elif df.l==b and df.n==1:
    df.v='val3'
elif df.l==b and df.n==2:
    df.v='val4'

回答1:

You can simply write them out with a boolean mask:

df.loc[(df.l == 'a') & (df.n == 1), 'v'] = 'val1'
df.loc[(df.l == 'a') & (df.n == 2), 'v'] = 'val2'
df.loc[(df.l == 'b') & (df.n == 1), 'v'] = 'val3'
df.loc[(df.l == 'b') & (df.n == 2), 'v'] = 'val4'

In [11]: df
Out[11]:
   g  l  n     v
0  0  a  1  val1
1  0  b  2  val4
2  0  a  1  val1
3  0  c  2     y
4  0  b  2  val4
5  1  b  1  val3
6  1  a  2  val2
7  1  b  1  val3
8  1  b  1  val3
9  1  a  2  val2

In more generality you can use enumerate and itertools.product (similar to Philip's answer):

from itertools import product
lhs_values, rhs_values = ['a', 'b'], [1, 2]
for i, (lhs, rhs) in enumerate(product(lhs_values, rhs_values)):
    df.loc[(df.l == lhs) & (df.n == rhs), 'v'] = 'val%s' % (i + 1)

Perhaps you'd just use the unique column values:

for i, (lhs, rhs) in enumerate(product(df.l.unique(), df.n.unique())):
    df.loc[(df.l == lhs) & (df.n == rhs), 'v'] = 'val%s' % (i + 1)

In [21]: df
Out[21]:
   g  l  n     v
0  0  a  1  val1
1  0  b  2  val4
2  0  a  1  val1
3  0  c  2  val6
4  0  b  2  val4
5  1  b  1  val3
6  1  a  2  val2
7  1  b  1  val3
8  1  b  1  val3
9  1  a  2  val2


回答2:

I'm not sure if you're just giving an example DataFrame or this is your actual DataFrame, but your conditions are a Cartesian product which you can construct using itertools and loop over the left and right hand side, along with that pair's replacement.

from itertools import product

lhs_values = 'a', 'b'
rhs_values = 1, 2
rep_values = ['val%d' % d for d in range(1, 5)]

lhs_rhs = list(product(lhs_values, rhs_values))
it = zip(*(zip(*lhs_rhs) + [tuple(rep_values)]))

for lhs, rhs, rep in it:
    df.v[(df.l == lhs) & (df.n == rhs)] = rep


回答3:

A different approach using map:

value_map = {
             ('a', 1): 'val1',
             ('a', 2): 'val2',
             ('b', 1): 'val3',
             ('b', 2): 'val4'
            }

df.v = map(value_map.get, zip(df.l, df.n))

EDIT: An alternative following Phillip Cloud's comment: if you want to keep the original df.v values in case there is no match in the dictionary, you can do this instead:

df.v = map(lambda x, y, z: value_map.get((x, y), z), df.l, df.n, df.v)