Tristan Forward
Tristan Forward

Reputation: 3514

Python Pandas: Changing One column based on another dynamically

I have the following array:

Key, Value

Up, a
Up, b
Up, b_regen
Up, c_regen
Down, a
Down, b
Down, b_regen
Down, c

Where Value == *_regen change Key to (key)_regen *being wildcard

Output would be:

Up, a
Up, b
Up_regen, b_regen
Up_regen, c_regen
Down, a
Down, b
Down, c
Down_regen, b_regen

I have gotten this far:

x = df['Key'].values[df['Values'].values == 'b_regen'] = 'Up_regen'

This works however it's not dynamic. I need the Up/Down _regen part not to be hard coded as above. Ideally the 'b_regen' value would also not be hard coded and would look for any variable with '_regen' in it. However I think I can get a workaround if I make it into a function.

Upvotes: 0

Views: 434

Answers (1)

Mike
Mike

Reputation: 7203

If you have a DataFrame like this:

a = pandas.DataFrame([['Up', 'a'], ['Up', 'a_regen'], ['Down', 'b_regen']], columns=['key', 'value'])
>>> a
    key    value
0    Up        a
1    Up  a_regen
2  Down  b_regen

You can create a function that determines if the value column ends in '_regen' and then apply it your values:

def is_regen(s):
    return s[-5:] == '_regen'

then just add the string to the end of your keys:

a.loc[a['value'].apply(is_regen), 'key'] += '_regen'
>>> a
          key    value
0          Up        a
1    Up_regen  a_regen
2  Down_regen  b_regen

Upvotes: 2

Related Questions